Fileupload Makes application Stops - android

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.

Related

Cordova Android: Empty request while uploading file using official cordova-plugin-file-transfer

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.

Global Variable undefined phonegap

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

Cordova fileTransfer works perfect on iOS, throws error code = 1 on Android

I'm developing a mobile app for iOS and Android using Cordova and Ionic Framework. There needs to be 'Send Photo' and related functionality, and I'm using Cordova's FileTransfer to do this.
It works perfectly on iOS simulator, but throws "error code = 1" on Android device.
I know this means file_not_found or similar.
Note it happens if I take a picture from camera, or choose one from gallery.
Here is my code:
$scope.takePic = function() {
var options = {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: 0, // 0:Photo Library, 1=Camera, 2=Saved Photo Album
encodingType: 0 // 0=JPG 1=PNG
}
navigator.camera.getPicture(onSuccess, onFail, options);
}
var onSuccess = function(FILE_URI) {
window.resolveLocalFileSystemURL(FILE_URI, function(fileEntry) {
alert("full: " + JSON.stringify(fileEntry));
var realUrl = fileEntry.toURL();
$scope.picData = realUrl;
$scope.$apply();
console.log("real URL", realUrl);
});
};
var onFail = function(e) {
console.log("On fail " + e);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
Flash.success("Wysłano");
var response = JSON.parse(r.response);
$scope.attachment_id = response.data;
$scope.$apply();
$http.post($rootScope.baseServerUrl + 'Members/changeAvatar', {attachment_id: response.data}).success( function (response){
console.log(response);
});
}
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);
}
$scope.send = function() {
Flash.warning('wysyłam');
var myImg = $scope.picData;
alert(myImg);
var options = new FileUploadOptions();
options.headers = {
Accept: "application/json",
Connection: "close"
}
options.fileKey="file";
options.fileName=$scope.picData.substr($scope.picData.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(myImg, encodeURI($rootScope.baseServerUrl + 'media/Attachments/add'), win, fail, options);
}
$scope.takePic and send are called by button clicks. There are a lot of alerts and console because I'm trying to find why its not working.
After picking a picture from the gallery on android I get:
file:///storage/sdcard0/download/file-name.jpg
on iOS simulator:
file:///Users//Library/Application%20Support/iPhone%20Simulator/7.1/Applications/B5FB2081-54E7-4335-8856-84C6499E6B07/tmp/cdv_photo_038.jpg
and by using this path I can show this picture by using <img src="{{picData}}"> this works on both platforms.
But if I try to send it on an Android device I get error Code = 1. On iOS sim it sends, photo, gets proper response, changes avatar...everything.
Both Cordova and plugins File and FileTransfer are up to date.
It looks like you might have a path error, file:///storage.sdcard0/download/file-name.jpg should be file:///storage/sdcard0/download/file-name.jpg if I'm not mistaken.
From perusing your code, it doesn't appear that you are parsing anything incorrectly. Maybe you want to try using an older more stable version of the file plugin if it is returning the wrong URI (and maybe file a bug report)? I haven't used the file plugin since they released 1.0, but from personal experience there have been bugs/regressions in the bleeding edge releases before.
You can target specific plugin versions from the cordova-cli using # like cordova plugin add org.apache.cordova.file#1.0.0
As well as specific tags/releases from github using # like cordova plugin add https://github.com/apache/cordova-plugin-file-transfer#r0.4.2
Maybe late but I've kinda fixed it.
In my view file I use:
<input id="file" name="file" type="file" onchange="angular.element(this).scope().addFile(this)" class="upload" accept="image/*" capture="camera"/>
so it fires $scope.addFile() from my controller as soon as you pick up file from galery:
$scope.addFile = function(item){
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
$scope.imgId = JSON.parse(evt.target.responseText).data;
$scope.$apply();
$http.post($rootScope.baseServerUrl + 'Members/changeAvatar', {attachment_id: $scope.imgId}).success( function (response){
console.log(response);
$scope.User.attachment_id = $scope.imgId;
$scope.$apply();
});
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.")
};
var updateImage = function (element) {
$scope.$apply(function() {
$scope.theFile = element.files[0];
var formData = new FormData();
formData.append("file", $scope.theFile);
var xhr = new XMLHttpRequest()
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.open("POST", $scope.baseServerUrl + "media/Attachments/add")
xhr.setRequestHeader("Accept","application/json")
$scope.progressVisible = true
xhr.send(formData);
});
};
updateImage(item)
}
Works for all Android devices I tested, above 4.0 excluding 4.4 because of input type="file" bug, works on iOS simulator and devices with 8.1 system (should also on older but I didn't test it).
It's not a perfect solution, because you can use only pictures you already got on your phone. I couldnt figure it out how to use Cordova FileTransfer with our server authentication way: I was always getting "please log in" in response, even when I tried adding all needed headers, tokens, anything...
So even though this solution is far from what I wanted to achieve - it works. Hope it helps anyone.

Phonegap android file to base64 out of memory error

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"

send file to server with phonegap

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.

Categories

Resources