2016-06-18 186 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); 
    }  
}