我尝试将请求发送到Cognitive Face Detect API,但始终收到空响应。我使用json发送请求没有问题,但是使用blob发送请求。我寻找并发现有人提供将base64转换为blob的代码。这是我的代码:
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src ='https://pmcvariety.files.wordpress.com/2017/04/willsmith_actor.jpg';
var imgurl = myCanvas.toDataURL('image/jpeg');
makeblob = function (dataURL) {
var BASE64_MARKER = ';base64,';
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
body = makeblob(imgurl);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://canadacentral.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true', true);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.setRequestHeader("Ocp-Apim-Subscription-Key", "my key here");
xhr.onload = function (oEvent) {
if (this.status == 200) {
alert(this.response);
}
}
xhr.send(body);