I'm building a mobile app for Android with JQM and PhoneGap. I need to upload a file (image) to remote server (from galery or take a picture with camera). Basically it can be done using phonegap file API, the problem is that the server was written to support simple POST submission.
What I need is to "simulate" in my app request exact as it would sent from the following html form. In addition I need to get the server response.
<form name="myWebForm" ENCTYPE="multipart/form-data" action="http://www.myurl.com/api/uploadImage "method="post">
<input type="file" name="image" />
<input type="submit" value="Submit"/>
</form>
I tried to use phonegap file API but the structure of the retrieved data on the server side is different than it should be.
I tried to implement that form in my app but the "choose file" button was disabled...
How it can be achieved without making any changes on the server side?
You can't use input file on Phonegap. It's not supported. You need make something like this:
function onDeviceReady() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('get picture failed'); },
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.png';
options.mimeType="text/plain";
var params = new Object();
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
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);
}
On getPicture method you will choose what's your file source. See more info: http://docs.phonegap.com/en/2.1.0/cordova_file_file.md.html#FileTransfer
EDIT:
The fileName extension was needed specify as well as the mimeType is requested on 'text/plain' format to send image on text format. As for the params, if you don't need them why use them?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With