2016-06-18 109 views
2

我想從移動設備上傳圖像到微軟計算機視覺API,但我不斷收到一個400錯誤的請求無效文件格式「輸入數據不是一個有效的圖像」。文檔指出我可以發送該數據作爲應用程序/八位字節流以下列形式:微軟認知服務:上傳圖片

[二進制圖像數據]

我的圖像的數據在base64編碼的術語( 「/ 9j/4AAQSkZJ ..........」),我也有一個FILE_URI的圖像,但我似乎無法弄清楚發送數據的格式。下面是一個示例代碼:

$(function() { 
    $.ajax({ 
     url: "https://api.projectoxford.ai/vision/v1.0/describe", 
     beforeSend: function (xhrObj) { 
      // Request headers 
      xhrObj.setRequestHeader("Content-Type", "application/octet-stream"); 
      xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", computerVisionKey); 
     }, 
     type: "POST", 
     // Request body 
     data: base64image, 
     processData: false   
    }) 
    .done(function(data) { 
     alert("success"); 
    }) 
    .fail(function(error) { 
     alert("fail"); 
    }); 
}); 

我已嘗試以下步驟:

  • [base64image]
  • {base64image}
  • 「數據:圖像/ JPEG; BASE64,」 + base64image
  • 「圖像/ JPEG; BASE64,」 + base64image

等等。

我在計算機視覺API控制檯上測試了這些。是否因爲base64編碼的二進制文件不是可接受的格式?或者,我是否以完全不正確的格式發送它?

注意:該操作在以application/json方式發送URL時起作用。

回答

1

只是想補充一點,以防其他人幫助。上述cthrash引用的答案工作正常,但它導致我更簡單的方式,不會將圖像轉換爲base64,然後返回到二進制。

只需將圖像作爲ArrayBuffer讀取,然後使用它爲帖子正文構造一個新的Blob。另外,不要忘記將processData設置爲false。完整的解決方案如下所示:

//onChange event handler for file input 
function fileInputOnChange(evt) { 
    var imageFile = evt.target.files[0];  
    var reader = new FileReader(); 
    var fileType; 

    //wire up the listener for the async 'loadend' event 
    reader.addEventListener('loadend', function() { 

     //get the result of the async readAsArrayBuffer call 
     var fileContentArrayBuffer = reader.result; 

      //now that we've read the file, make the ajax call 
      $.ajax({ 
       url: "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect", 
       beforeSend: function (xhrObj) { 
        // Request headers 
        xhrObj.setRequestHeader("Content-Type", "application/octet-stream"); 
        xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "<your subscription key goes here>"); 
       }, 
       type: "POST", 

       //don't forget this! 
       processData: false, 

       //NOTE: the fileContentArrayBuffer is the single element 
       //IN AN ARRAY passed to the constructor! 
       data: new Blob([fileContentArrayBuffer], { type: fileType }) 
      }) 
      .done(function (data) { 
       console.log(data) 
      }) 
      .fail(function (err) { 
       console.log(err) 
      }); 

    }); 
    if (imageFile) { 
     //save the mime type of the file 
     fileType = imageFile.type; 

     //read the file asynchronously 
     reader.readAsArrayBuffer(imageFile); 
    }  
}