我正在尝试构建一个移动应用程序(带有Cordova和html5的混合应用程序,不是本机的,这是javascript代码!),允许使用Cloudsight等外部服务API拍照和搜索图片内容(文档在这里:https://cloudsight.readme.io/docs/testinput)。根据他们的文档,请求应该通过 URL 使用远程图像(完美运行)或作为多部分表单请求部分附加的本地图像来完成,因为我想用从手机拍摄的照片来做到这一点我想附加我的本地图像,但我找不到如何做到这一点!这是我的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);
}
});
您可以将包含表单数据的图像作为多部分发送。
您需要使用 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
);