0

我正在尝试构建一个移动应用程序(带有cordova和html5的混合应用程序,不是本机,这是javascript代码!)允许拍照并使用cloudsight之类的外部服务API搜索图片的内容(文档在这里:https://cloudsight.readme.io/docs/testinput)。根据他们的文档,一个请求应该通过 URL 使用远程图像(效果很好)或作为 multipart-form-request 部分附加的本地图像完成,因为我想用我想要的手机拍摄的照片来完成此操作附上我的本地图片,但我不知道该怎么做!这是我的 jQuery Ajax 调用代码,$scope.lastPhoto 是一个带有我本地图片文件 URI 位置的字符串(如“file://asdasd/asdsad/dsa/pic.jpg”),我如何将它作为多部分发送 -表单请求部分?

$.ajax({
        method: "POST",
        url: "https://api.cloudsightapi.com/image_requests",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "CloudSight mykeywhichiwontshowtoyou");
        },
        data: {
            //I've tried this syntax but doesnt work
            'image_request[image]': new FormData().append('file', $scope.lastPhoto),

            //This doesnt work neither since it's just my local pic address
            //'image_request[image]': $scope.lastPhoto,

            //request with a remote image that actually works
            //"image_request[remote_image_url]": "http://pf.pfgcdn.net/sites/poltronafrau.com/files/styles/scheda_prodotto_gallery/public/content/catalogo/any_case/immagini/anycase.jpg",
            "image_request[locale]": "en-US"
        },
        success: function (msg) {
            $scope.token = msg.token;
        },
        error: function (msg) {
            console.log(msg.responseText);
        }
    });
4

1 回答 1

-1

您可以将带有表单数据的图像作为多部分发送。

您需要使用 FileTransferPlugin。它以多部分形式发送带有表单数据的图像数据。

首先是从相机/图库中捕获文件并成功保存:

         fileURL=imageData;

然后,要将表单提交到服务器,这里是代码片段。

        var params = {};
        params.username= "coolUser";
        params.userage = 12;

        var uploadOptions = new FileUploadOptions();
        var ft = new FileTransfer();

        uploadOptions.fileKey = "expectedNameOUploadFile";
        uploadOptions.fileName = fileName; // name of the file
        uploadOptions.mimeType = "image/jpeg"; 
        uploadOptions.httpMethod = "POST";
        uploadOptions.params = params;

        ft.upload(fileURL,
            serviceURL,
            photoSuccess,
            photoFail,
            uploadOptions,
            true
        );
于 2016-03-07T11:28:51.380 回答