认知服务计算机视觉API返回'缓存控制错误'

时间:2017-03-04 17:32:19

标签: javascript api computer-vision microsoft-cognitive

我试图在JavaScript中使用Microsoft Cognitive Service计算机视觉API。我必须将画布图像上传到API并获得结果。 我在' param'中使用了相同的程序。和' URL'使用Face API进行更改,它运行正常。但在Computer Vision API中它给出了这个错误: " Cache-Control:no-cache \ r \ nPragma:no-cache \ r \ nContent-Type:application / json; charset = utf-8 \ r \ nExpires:-1 \ r \ n"

我的代码是:



var apiKey = "<KEY>";
var apiUrl = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect";
var params = {
            // Request parameters
            "maxCandidates": "1",
        };
        
$('#btn').click(function () {
 	var file = document.getElementById('filename').files[0];
 	CallAPI(file, apiUrl, apiKey);
    


 });
 
navigator.getUserMedia = ( navigator.getUserMedia ||
                        	navigator.webkitGetUserMedia ||
                            navigator.mozGetUserMedia ||
                            navigator.msGetUserMedia);

var video;
var webcamStream;
function startWebcam() {
    if (navigator.getUserMedia) {
		navigator.getUserMedia (
           	{
                video: true,
                audio: false
            },

        	function(localMediaStream) {
                	video = document.querySelector('video');
                	video.src = window.URL.createObjectURL(localMediaStream);
                 	webcamStream = localMediaStream;
              	},

            function(err) {
                 	console.log("The following error occured: " + err);
              	}
        );
    } 
    else {
    	console.log("getUserMedia not supported");
    }  
}

function stopWebcam() {
          webcamStream.stop();
      	}

makeblob = function (dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = decodeURIComponent(parts[1]);
        return new Blob([raw], { type: contentType });
    }
    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 });
}


function snapshot() {
	canvas = document.getElementById("myCanvas");
	ctx = canvas.getContext('2d');
	ctx.drawImage(video, 0,0, canvas.width, canvas.height);
	var dataurl= canvas.toDataURL();
	CallAPI(dataurl, apiUrl, apiKey);
}
setInterval(snapshot,10000);


function CallAPI(file, apiUrl, apiKey)
{	console.log("api called");
	 $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",apiKey);
            },
			type: "POST",
			data: makeblob(file),
			processData: false
		})

	.done(function (response) {
			ProcessResult(response);
			console.log("done");
	})

	.fail(function (error) {
			$("#response").text(error.getAllResponseHeaders());
            var str= JSON.stringify(error.getAllResponseHeaders())
			console.log(str);
	});
}
 
function ProcessResult(response)
{
	// var data = JSON.parse(response);
    var string= JSON.stringify(response);
    var string = string.substring(1, string.length-1);
    var data= JSON.parse(string);
    console.log(string)   

}
&#13;
&#13;
&#13;

请帮助并建议更好的方法来做到这一点。

1 个答案:

答案 0 :(得分:0)

在$ .ajax通话中,Content-Type需要设置为application/octet-stream

另外提醒一下,Vision和Face API具有不同的API密钥。

$.ajax({
    url: apiUrl + "?" + $.param(params),
    beforeSend: function(xhrObj){
        // Request headers
        xhrObj.setRequestHeader("Content-Type","application/octet-stream");
        xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", apiKey);
    },
    type: "POST",
    data: makeblob(file),
    processData: false
})