How to upload file with Phonegap and JqueryMobile?

前端 未结 2 1601
一个人的身影
一个人的身影 2020-12-05 20:40

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

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 21:00

    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?

提交回复
热议问题