How to upload file with Phonegap and JqueryMobile?

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("https://stackoverflow.com/")+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?

Leave a Comment