这是今天在黑客松现场写的代码。我们的项目需要调用认知服务的情感识别接口。官方提供了一种方式,就是从一个远程图片进行识别。我另外写了一个从本地文件读取并上传进行识别的例子。
官方文档,请参考 https://docs.azure.cn/zh-cn/cognitive-services/emotion/quickstarts/javascript
$(function () {
$("#test").click(function () {
var params = {
// Request parameters
};
$.ajax({
url: " https://api.cognitive.azure.cn/emotion/v1.0/recognize" + $.param(params),
beforeSend: function (xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
// NOTE: Replace the "Ocp-Apim-Subscription-Key" value with a valid subscription key.
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "换成你的 key");
},
type: "POST",
// Request body
data: '{"url": " https://tse3.mm.bing.net/th?id=OIP.4M-jZG7HnQUpUKJ0wowq7QDrEs&pid=1.7"}' ,
})
.done(function (data) {
console.log(data)
})
.fail(function () {
alert("error");
});
});
});
Text File Reader
Select a text file:
window.onload = function () {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function (e) {
// Put the rest of the demo code here.
var file = fileInput.files[0];
var textType = /image.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
var params = {
// Request parameters
};
$.ajax({
url: " https://api.cognitive.azure.cn/emotion/v1.0/recognize?" + $.param(params),
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "换成你的 key");
},
type: "POST",
data: reader.result,
processData: false
})
.done(function (data) {
alert("success");
})
.fail(function () {
alert("error");
});
}
reader.readAsArrayBuffer(file);
}
else {
fileDisplayArea.innerText = "File not supported!";
}
});
}
来源: http://www.cnblogs.com/chenxizhang/p/8046542.html