I want to send files to the server using PhoneGap. here is my code below the following function parameter file to send. the problem that if I insert a fake url as localhost server it shows me server error code = 2, and if I insert a real url displays me file not found code = 1
function gotFile(file)
{
navigator.notification.alert(file.fullPath);
var options = new FileUploadOptions();
options.mimeType="image/jpg";
options.fileKey="file";
var params = {};
params.IdPrestation = "3d660013-3028-46c3-adfa-d7141a712ed7";
params.IdPhoto = "3a660013-3028-46c3-adfa-d7141a712ed7";
options.params = params;
options.chunkedMode = true ;
var ft = new FileTransfer();
ft.upload(file.fullPath,encodeURI('http://Myserver.fr/Phototheque.asmx/SavePhoto'),function(r)
{
//navigator.notification.alert(r.response,function(){});
alert(r.response,function(){});
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
},
function(e)
{
//navigator.notification.alert('Serveur Erreur:' + e.code,function(){});
cause_erreur(e.code);
/*
alert('Serveur Erreur:' + e.code,function(){});
alert("upload error source " + e.source);
alert("upload error target " + e.target)
*/
},
options
);//ft.upload
}
I do not exactly know your bug. However, your uploading code seems to be normal and the error may occur because of the file size or the network state.The same time, you can check in server whether request and response work as expected.
Related
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.
Im developing an android application in phonegap, in which i click on button , i take a picture from photo library of the device. i display it in my application then a pop up is shown asking me if i want to confirm uploading the image to server (I use Filetransfer to upload the image).
Everything is working fine , except one thing. when can take the picture , i display it and i can upload it. the problem now that when i upload the picture , in my win(r) function i have a variable "r.response" , i should send it to the server. that's why i create a global variable "imageServer" that takes the values of r.response and i call it from another function. but when i alert it tells me undefined. Here is my code.
var imageServer;
function uploadPhoto(imageData)
{
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageData.substr(imageData.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageData, encodeURI("Server Url"), win, fail, options);
}
function win(r)
{
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
imageServer = r.response;
//alert(imageServer);// Here when i alert i should get the url of the picture
console.log("Sent = " + r.bytesSent);
}
function fail(error)
{
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
function SendServer()
{
alert(imageServer); // when i alert here i get undefined
var callDatasetPosition = JSON.stringify({'serviceName':"global_functions", 'methodName':'setPosition',"parameters":[imageServer]});// here when i see in server side , there is no url of image send
$.post('server url', callDatasetPosition, function(resp){}).done(function(data)
{
console.log(data);
alert(data);
});
}
Can you help me please. Thanks a lot
I am attempting to get a video file on android, convert it to base64 encoding and upload it.
When the file is larger than 5Mb, I get out of memory error in android, but ios convert large files also. Only in android I got this error....
This is my code:
var reader = new FileReader();
reader.onload = function(evt1) {}, reader.onloadend = function(evt) {
console.log("read success");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
You should be aware that the base64-encoded data will be roughly 37% larger than the original data size. Considering that you're dealing with large files and the base64-encoding causes out of memory errors, I would not encode it with base64.
It's not a good idea to read large files at once. Instead, I recommend streaming your file to the server. With this approach, the file will be read and transferred in chunks, preventing out of memory errors and avoiding lags on slower devices. You can do this for example using the FileTransfer object with chunkedMode enabled in the FileUploadOptions.
Recommended approach (adapted from the documentation):
// !! Assumes variable fileURI contains a valid URI to a H.264/AVC video on the device
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.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "video/avc"; //change to the according mimeType
options.chunkedMode = true; //upload the data in chunked streaming mode (true by default)
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
create php.ini file on server side and add following code. You can increase upload_max_filesize
register_globals = on
display_errors = Off
error_reporting = E_ALL & E_NOTICE & E_WARNING & E_DEPRECATED
upload_max_filesize = 50M
memory_limit = 500M
max_execution_time = 1800
post_max_size = 120M
session.gc_maxlifetime = 86400
error_log = /var/log/php-scripts.log
#safe_mode = Off
#safe_mode_exec_dir = "storage_dir_path"
#open_basedir = "storage_dir_path"
Here the code which i have used in my corodova 2.9.0 based application in Andorid .When i try to upload the photo.The Application gets crashed.
function uploadPhoto(imageURI)
{
Ext.Viewport.mask({ xtype: 'loadmask' });
var milliseconds = js_yyyy_mm_dd_hh_mm_ss();
var options = new FileUploadOptions();
options.fileKey="file";
options.chunkedMode=false; options.fileName=App.gvars.userid+milliseconds+imageURI.substr(imageURI.lastIndexOf('/')+1);
renamedfile=options.fileName;
options.mimeType="image/jpeg";
var params = new Object();
options.params = params;
var ft = new FileTransfer();
var url = "http://wish.brammies.com/itemimage/upload.php/";
ft.upload(imageURI, url, win, fail, options,true);
}
function win(r)
{
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error)
{
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
EDIT
PHP code
<?php
$folder = “/itemimage/”;
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $folder.$_FILES['file']['name'])) {
echo "File uploaded";
} else {
echo "File not moved to destination folder. Check permissions";
};
} else {
echo "File is not uploaded.";
};
//you get the following information for each file:
echo $_FILES['file']['name']."</br>"; //represents the name of file uploaded
echo $_FILES['file']['size']."</br>"; //represents the size of file uploaded
echo $_FILES['file']['type']."</br>"; //represents the mime type of file uploaded
echo $_FILES['file']['tmp_name']."</br>";
echo "fdggdr";
?>
Android running version 4.1.4
Please help me to solve the issue.
set options.chunkedMode=true;
When chunked mode is false the HTTP code on Android tries to buffer the entire transfer in memory before sending. With larger transfers 15 mb in your case but for other phones it will be even less as they will have less memory this will cause an OutOfMemory Exception to be thrown. Since an OOME should never be caught the application will crash.
I'm triing to upload a file with phonegap to streamwork ( https://streamwork.com/api/Post_an_item_File_item.html ) .
I tried Phonegap's FileTransfer api which does not seem to send the request like streamwork wants it to:
var url =getItemsURL();
var item = "<?xml version='1.0' encoding='UTF-8'?>" +
"<item name='Test "+timestamp()+"'>" +
"<description>my upload</description>" +
"<file_item/>" +
"</item>";
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);
}
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName="hello.txt";
options.mimeType="text/plain";
var params = new Object();
params.item = item;
options.params = params;
var paths = navigator.fileMgr.getRootPaths();
var ft = new FileTransfer();
ft.upload(paths[0] + "hello.txt",url, win, fail, options);
</code>
(actually I see that phonegap internally throws "java.io.FileNotFoundException: https://streamwork.com/v1/activities/..."
But the url should be correct since I then used the same in a manually written xhr.
function doUpload(data,fname,type,enc){
var url = getItemsURL();
var item = "<?xml version='1.0' encoding='UTF-8'?>" +
"<item name='My new activity item "+timestamp()+"'>" +
"<description>my upload</description>" +
"<file_item/>" +
"</item>";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
alert("xmlHttpObject.readyState = " + xhr.readyState + (xhr.readyState >= 3 ? " HTTP-Status = " + xhr.status : ''));
};
xhr.open("POST",url, true);
var boundary ="mime_boundary"
xhr.setRequestHeader("Accept", 'application/xml');
xhr.setRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary);
var body = '--' + boundary + '\r\n';
body+='Content-Disposition: form-data; name="item"; filename="dummy.xml"\r\n';
body+= 'Content-Type: application/xml\r\n\r\n';
body+=item+'\r\n';
body+='--'+boundary+'\r\n\r\n';
body+='Content-Disposition: form-data; name="file"; filename="'+fname+'"\r\n';
body+='Content-Type: '+type+'\r\n';
body+='Content-Transfer-Encoding: '+enc+'\r\n\r\n';
body+=data+'--' + boundary + '--\r\n';
xhr.setRequestHeader('Content-length', body.length);
xhr.send(body);
}
which I call with
doUpload("lorem ipsum foo bar","test.txt","text/plain","binary");
this works in firefox when I give it the privilege to to cross domain stuff, but when I execute it on my android (htc desire hd) it does not work.
Firefox xhr readystate change outputs are: 1, 1, 2, 4(0)
Android xhr readystate change outputs are: 1, 4(0)
Does anyone has an idea, on what I am missing?
Thanks in advance
max