2016-05-16 72 views
0

我有一個REST API調用的以下示例 -如何將給定的curl命令複製爲jquery ajax請求?

curl -u "{username}":"{password}" -X POST \ 
-F "[email protected]" \ 
"https://gateway.watsonplatform.net/visual-recognition-beta/api/v2/classify?version=2015-12-02" 

我想執行上述呼叫作爲標準的AJAX請求。這是我迄今爲止 -

cropper.getCroppedCanvas().toBlob(function(blob){ 
     var uploadData = new FormData(); 
     uploadData.append('images_file',blob); 

     $.ajax('https://gateway.watsonplatform.net/visual-recognition-beta/api/v2/classify?version=2015-12-02', { 
     method: "POST", 
     data: uploadData, 
     processData: false, 
     contentType: false, 
     beforeSend: function (xhr) { 
      xhr.setRequestHeader('Authorization', 'Basic ODdlOTTZIeg=='); 
     }, 
     success: function (data) { 
      console.log('Upload success'); 
      console.log(data); 
     }, 
     error: function (data) { 
      console.log('Upload error'); 
      console.log(data); 
     } 

    }) 

    }) 

我得到一個錯誤 -

"{"code":400,"error":"Could not classify. Verify that valid images were uploaded."}" 

我的直覺是,沒有被正確模擬了上述AJAX調用捲曲的-F [email protected]

cropper.getCroppedCanvas()是一個來自cropperjs庫的函數調用。

回答

0

使用formDatablob與這樣的:

formdata.append("myfile", myBlob, "filename.txt"); 

Document參見

當使用append()方法,可以使用第三可選參數傳遞內容 - 內的文件名處理標題發送到服務器。如果未指定文件名(或者不支持該參數),則使用名稱「blob」。

因此,對於您的情況:

cropper.getCroppedCanvas().toBlob(function(blob){ 

    var uploadData = new FormData(); 

    var filename = "your-file-name-with-suffix"; 
    uploadData.append('images_file',blob,filename); 

    //$.ajax(...); 
});