通过Javascript调用微软认知服务情感检测接口的两种实现方式
这是今天在黑客松现场写的代码。我们的项目需要调用认知服务的情感识别接口。官方提供了一种方式,就是从一个远程图片进行识别。我另外写了一个从本地文件读取并上传进行识别的例子。
官方文档,请参考 https://docs.azure.cn/zh-cn/cognitive-services/emotion/quickstarts/javascript
第一种方式,使用远程的图片文件
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/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");
});
});
});</script>
</head>
<body>
<button id="test">测试</button>
</body>
</html>
第二种方式,直接使用本地文件,读取二进制上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File Emotion detecting</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"></pre>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script>
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!";
}
});
}
</script>
</body>
</html>