i have problem to sync local image folder to server, i using titanium. When i run my program using android emulator, it works well. But when i try to run it using actual device, the program can not find the image file.
Below is my code. Please help.
$.btnfiles.addEventListener('click',function(e)
{
var dirTest = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory);
var dirList = dirTest.getDirectoryListing();
Titanium.API.info('Start loop for files length:' + dirList.length);
for ( i = 0; i < dirList.length; ++i){
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, dirList[i]);
var data_to_send = {
"file": f.read(), "name1":Titanium.Filesystem.applicationDataDirectory
};
xhr = Titanium.Network.createHTTPClient({
// function called when an error occurs, including a timeout
onerror : function(e) {
//Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.open("POST","upload.php");
xhr.send(data_to_send);
Titanium.API.info('Namef: ' + dirList[i]);
Titanium.API.info('Name: ' + i);
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,dirList[i]);
if (file.exists()) { file.deleteFile(); }
}
});
Related
I'm creating an Hybrid app in which I want to upload video to
server. Sometimes it uploads the video to the server but most of the
time Plugin shows the uploading progress to 99% and then it gives
null in success callback.
Thanks in advance. :-)
/********* OPENING CAMERA TO CPTURE VIDEO ***********/
function make_Video()
{
// capture callback
var captureSuccess = function(mediaFiles) {
var i, len , video_path;
if(mediaFiles.length > 0)
{
for (i = 0, len = mediaFiles.length; i < len; i += 1)
{
video_path = mediaFiles[i].fullPath;
Upload_Video(video_path);
}
}
};
// capture error callback
var captureError = function(error)
{
console.log('Error Code: ' + error.code);
};
navigator.device.capture.captureVideo(captureSuccess, captureError, { quality: 100,destinationType: Camera.DestinationType.FILE_URI });
}
/****************STORING VIDEO ON SERVER******************/
function Upload_Video(video_path)
{
var server = server_link; // MY SERVER LINK
var params = {'user_id':logged_in_user_id,'action':'update_intro_video'};
if (server)
{
// Specify transfer options
$('#modal_first_line').text(0+" %"+" Uploaded");
$('#new_modal').show();
var options = new FileUploadOptions();
options.fileKey = "user_video";
options.fileName = video_path.substr(video_path.lastIndexOf('/')+1);
options.mimeType = "video/mp4";
options.chunkedMode = false;
options.httpMethod = "POST";
options.params = params;
// Transfer picture to server
var ft = new FileTransfer();
//progree bar
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable){ var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); $('#modal_first_line').text(perc+" %"+"
Uploaded"); } else {$('#new_modal').hide();
console.log("sorry! Upload Failed..."); } };
ft.upload(video_path, encodeURI(server) , function(data) {
$('#new_modal').hide();
console.log("SERVER RESPONSE: " + JSON.stringify(data));
},
function(error)
{
$('#new_modal').hide();
console.log("sorry! Upload Failed...");
}, options);
}
else{
$('#new_modal').hide();
console.log("sorry! Can't Upload File.");;
}
}
Solved.
The Problem was at server end. Configuration was making
trouble. post_max_size was set to 8Mb, so when limit of video
exceeds to 8MB, server was not allowing to save the video. I
increased the post_max_size to 100MB. To Increase the post_max_size
, I did the following steps
1. I Created a file .user.ini in the root directory
2. I placed the following code inside this file
file_uploads = O post_max_size = 100M upload_max_filesize
= 200M
Hope it will help someone.
Trying to upload a file to a server using the official cordova-plugin-file-transfer provided by Apache at https://github.com/apache/cordova-plugin-file-transfer.
Created an empty cordova project, setup file picker (https://github.com/don/cordova-filechooser) and file uploader, and ran the following code:
function servUpload(fileURL) {
var win = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "upfile";
options.fileName = "test.jpg";
options.mimeType = "image/jpeg";
options.httpMethod = "POST";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://example.com/test.php"), win, fail, options);
}
function getFile() {
fileChooser.open(function(uri){
//alert(uri);
//document.getElementById('img1').setAttribute('src', uri);
console.log(uri);
servUpload(uri);
}, function(err){
console.log(err);
});
}
getFile();
(Note the post params I set).
My test.php contains the following (just echos back all of the file, post and get vars).
<?php
print_r($_FILES);
print_r($_POST);
print_r($_GET);
?>
The code runs fine, I can pick a file and it seems to take a bit to attempt to upload. But without any error the server picks up that it has not received any info from the client (no files, nor the POST params I set in the code):
Response = Array
(
)
Array
(
)
Array
(
)
A simple post request works though:
var http = new XMLHttpRequest();
var url = "http://example.com/test.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
This returns:
Array
(
)
Array
(
[lorem] => ipsum
[name] => binny
)
Array
(
)
I'm at a loss for what I can do, I've made sure that the file picker actually works (I've been testing with an image file and tested that I can set an <img> element with the image as its source).
Any ideas? Thanks in advance.
Figured it out, wasn't a problem on cordova's end, my LEMP wasn't setup right. Cordova code works perfectly.
I am building a PhoneGap app, and currently have setup some datasources that have a JSON feed I pull from, to populate my app with data. Right now, it only pulls that data once, the first time the app is run.
I would like to download data everytime the app first opens, and then if it stays open for longer than 15 minutes, it updates again. The json feed can be queried with a last_mod_day in the URL so it pulls only the data that has changed.
What would be recommended to go about this, and how to check for a WiFi/Data Connection on the phone, and if not it fails quietly?
Below is the code for my current function to grab the feed.
function downloadFileError(evt) {
console.log('downloadFileError: ');
console.log(evt.target.error);
}
function downloadFile(ep) {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile("dummy.json", {
create: true,
exclusive: false
},
function gotFileEntry(fileEntry) {
var filename = cordova.file.dataDirectory + 'assets/json/' + ep + '.json';
var fileTransfer = new FileTransfer();
fileEntry.remove();
console.log('looking at ' + filename);
fileTransfer.download(
encodeURI("http://www.myURL.com/theApp?ep=" + ep),
filename,
function(theFile) {
console.log("download complete: " + theFile.toURL());
},
function(error) {
console.log("DLERR: src=" + error.source + " t=" + error.target);
}
);
},
function(evt) {
console.log(evt);
console.log('fn: ' + filename);
}
);
},
downloadFileError);
}
function downloadDynamicPages() {
var deferred = $.Deferred();
var pages = ['setOne','setTwo','setThree','setFour','setFive','setSix'];
var cnt = 0;
var total_pages = pages.length;
//checkConnection();
$.each(pages,function(k,v) {
console.log('looking at ' + v);
downloadFile(v);
cnt++;
if(cnt >= total_pages) {
deferred.resolve('all done with files');
}
});
return deferred.promise();
}
Any help on any part of these questions would help me greatly. If needed, I can answer any questions. Thank you Stack.
Error in checking the file.
I have use one code. But i think there is some problem. The file got stuck to one file. And always keep dowloading the same file.
here is how i code this. Here in the below code. I am trying to download the images to local sdcard. If the file is already available i dont want it to download. And if not, then download. But it seems its just keep repeat download the same file.
function appReady(datadira){
$(".gallery").html("Ready to check remote files...");
$.get("http://www.pankhida.com/main/?json=get_page&page_id=115&callback=?", {}, function(res) {
if (res.page.attachments.length > 0) {
$(".gallery").html("Going to sync some images...");
for (var i = 0; i < res.page.attachments.length; i++) {
if (knownfiles.indexOf(res.page.attachments[i].url) == -1) {
//alert("need to download " + res[i]);
var ft = new FileTransfer();
var fullPath = res.page.attachments[i].url;
var filename = fullPath.replace(/^.*[\\\/]/, '');
var dlPath = DATADIR.toURL() + "/" + filename;
var uri= res.page.attachments[i].url;
uri = encodeURI(uri);
//console.log("downloading crap to " + dlPath);
window.resolveLocalFileSystemURL(DATADIR.toURL() +"/"+ filename, appStart, function(){
ft.download(uri, dlPath, function(e){
//renderPicture(e.toURL());
alert("Successful download of "+e.toURL());
}, onError, true);
});
}
}
}
$(".gallery").html("");
}, "json");
}
I am using window.resolveLocalFileSystemURL which i got from this URL http://www.raymondcamden.com/2014/7/1/Cordova-Sample-Check-for-a-file-and-download-if-it-isnt-there.
Please suggest where i am wrong. Or any correct code will be really helpful.
It has to do with the closure inside resolveLocalFileSystemURL.The value of ft ends up being the last one used from the loop. Try changing
for (var i = 0; i < res.page.attachments.length; i++) {
to
res.page.attachments.forEach(function(attachment) {
and the last } to }).
Inside the loop, use attachment instead of res.page.attachments[i].
I have the following piece of code:
function download_img(imgToDownload, imgToRemove){
var url = remote_url+imgToDownload; // image url
root_path = get_root_path();
var flag = "working";
var flag_delete = false;
var imageToDownloadPath = root_path + "/" + imgToDownload; // full file path
var imageToRemovePath = root_path + "/" + imgToRemove; // full file path
try{
var fileTransfer = new FileTransfer();
fileTransfer.download(url, imageToDownloadPath,
function () {
if(imgToRemove != "" && imgToRemove != null){
var entry = new FileEntry("foo", imageToRemovePath);
entry.remove(function (){alert("fine");flag_delete = true;}, function (){alert("marron");flag_delete = true;});
}
else{
flag_delete = true;
}
flag = "done";
},
function (error) {
flag = "done";
flag_delete = true;
}
);
}catch(error){
alert("Error capturado: "+error.message);
}
while(flag=="working" && !flag_delete){
try{
setTimeout(
function() {
/* Código */
},
300
);
}
catch(error){
alert("Error en el bucle: " + error.message);
}
}
}
I have had problems downloading the files which apparently seemed to be a sync conflict, I mean, looks like something was avorting the execution before the file/s was/were downloaded.
I have used two flags to make sure not to continue until files are downloaded (and old ones deleted if necessary). The idea is to change flag's values when the action is completed and keep the code waiting in a loop.
The results this code is giving is as follows:
It never seems to enter the success fileTransfer.download sucess method (I used an alert which never triggered) even though the first file downloads properly.
The flags are never changed so the code stays stuck in the loop, and it does not continue downloading other files.
I think it might be a very basic jQuery behaviour but I am just starting with this technologies and I am a little lost. If anyone could give me a clue on that I would really appreciate it.
Thanks!!