jQuery 如何使用Phonegap 和JqueryMobile 上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13861310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:01:18  来源:igfitidea点击:

How to upload file with Phonegap and JqueryMobile?

jquerycordovajquery-mobile

提问by Victor

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.

我正在使用 JQM 和 PhoneGap 为 Android 构建一个移动应用程序。我需要将文件(图像)上传到远程服务器(从画廊或用相机拍照)。基本上它可以使用phonegap文件AP​​I来完成,问题是服务器被编写为支持简单的POST提交。

What I need is to "simulate" in my app request exactas it would sent from the following html form. In addition I need to get the server response.

我需要的是在我的应用程序的要求“模拟”确切的,因为它会从以下HTML格式发送。另外我需要得到服务器响应。

<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.

我尝试使用 phonegap 文件 API,但服务器端检索到的数据的结构与应有的不同。

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?

如何在不对服务器端进行任何更改的情况下实现?

采纳答案by A. Magalh?es

You can't use input file on Phonegap. It's not supported. You need make something like this:

您不能在 Phonegap 上使用输入文件。不支持。你需要做这样的事情:

    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

在 getPicture 方法中,您将选择文件来源。查看更多信息: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?

需要指定 fileName 扩展名以及在“text/plain”格式上请求 mimeType 以发送文本格式的图像。至于参数,如果你不需要它们,为什么要使用它们?

回答by Rakesh Samal

You can't use input file on Phonegap. It's not supported. You need make something like this:

您不能在 Phonegap 上使用输入文件。不支持。你需要做这样的事情:

        <div ng-click="selectPicture()">selectPicture</div> // Put own HTML format but call the fuction

        // Angular fuction
             $scope.selectPicture = function () {
                var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
                var options = {
                    // Some common settings are 20, 50, and 100
                    quality: 50,
                    destinationType: Camera.DestinationType.FILE_URI,
                    // In this app, dynamically set the picture source, Camera or photo gallery
                    sourceType: srcType,
                    encodingType: Camera.EncodingType.JPEG,
                    mediaType: Camera.MediaType.PICTURE,
                    allowEdit: true,
                    correctOrientation: true  //Corrects Android orientation quirks
                }
                navigator.camera.getPicture(function cameraSuccess(imageUri) {
                    MobileUploadFile(imageUri);

                }, function cameraError(error) {
                    console.debug("Unable to obtain picture: " + error, "app");
                }, options);
            }

            function MobileUploadFile(imageURI) {
                //console.log(imageURI);   
                var options = new FileUploadOptions();
                options.fileKey = "file";
                options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
                options.mimeType="image/jpeg";
                options.chunkedMode = false;

                var ft = new FileTransfer();
                ft.upload(imageURI, encodeURI("http://www.example.com/upload.php"), function(result){
                    //console.log(JSON.stringify(result));
                }, function(error){
                    //console.log(JSON.stringify(error));
                }, options);
            };

     // php file
     <?php 
       // Directory where uploaded images are saved
        $dirname = "uploads/"; 
        // If uploading file
         if ($_FILES) {
             print_r($_FILES);
             mkdir ($dirname, 0777, true);
             move_uploaded_file($_FILES["file"]{"tmp_name"],$dirname."/".$_FILES["file"]["name"]);
        }
      ?>