Global Variable undefined phonegap - android

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

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.

Cordova FileUpload API returns error code 3

I am having problem trying to upload an image file to my local web server (hosted using wampserver) for android hybrid app built using IBM Worklight 6.2.0 with Cordova version 3.4.0. The code snippet is as below:
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
// Nothing here
}
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
}, {
quality: 40,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
});
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.168.1.4:8081/folder_name/upload2.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
</script>
<button onclick="getImage();">Upload a Photo</button>
upload2.php
<?php print_r($_FILES); $new_image_name="namethisimage.jpg" ; move_uploaded_file($_FILES[ "file"][ "tmp_name"], "folder_name/uploads/".$new_image_name); ?>
I'm getting http status 200 and an error code 3. Besides that, I also getting this error below the http status and error code error.
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:14584 from pid=4926, uid=10092 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
Is there any solution to this? Or is there a better way for me to upload the image file?
I've added the following to AndroidManifest.xml
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am not sure what's the issue here. My code just works suddenly, even with AngularJS. I will just share my working code here, if others might want to refer.
main.js
$scope.getImage = function() {
// Retrieve image file location from specified source
navigator.camera.getPicture(onSuccess, function(message) {
alert('get picture failed');
},{
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function onSuccess(imageURI) {
$scope.image = imageURI;
};
function uploadPhoto(image) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName= $scope.imageName;
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(image, encodeURI(ipaddress_to_your_server/root_folder/upload.php), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
upload.php
<?php
print_r($_FILES);
$image_name = $_FILES['file']['name'];
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$image_name);
?>
You will just need to call the $scope.getImage function in html to open the device's photo library.
Based on the last image, it seems that you solved this somehow - you should share it as an answer.
Regardless,
Why is there PHP code in your code snippet? Is this code snippet originating from your Worklight-based app? You cannot have there PHP... This is a mobile app, running in your device, not on your server. There is nothing there that will interpret that code.
The following should not be used in your app, because Cordova is part of the Worklight framework and this check is done internally. Instead, your code should sit inside the wlCommonInit() function in main.js, or be called from there.
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
// Nothing here
}
I suspect that is why nothing works for you. Try to use AJAX to make the request to the server, to receive the sent image and store it in your web server.

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.

Fileupload Makes application Stops

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.

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