這是今天在黑客鬆現場寫的代碼。咱們的項目須要調用認知服務的情感識別接口。官方提供了一種方式,就是從一個遠程圖片進行識別。我另外寫了一個從本地文件讀取並上傳進行識別的例子。javascript
官方文檔,請參考 https://docs.azure.cn/zh-cn/cognitive-services/emotion/quickstarts/javascriptcss
<!DOCTYPE html>
<html>
<head>
<title></title>html
<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");java
// 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>jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File Emotion detecting</title>ajax
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">json
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"></pre>api
</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');app
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>