0

我希望能够在我的网站上实现来自 Project Oxford 的 Emotion API。我目前编写了以下 HTML/JavaScript 代码,它检查来自 URL 的图像并在运行 Emotion API 后显示所述图像的结果:

<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
  $.ajax({
      url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
      beforeSend: function(xhrObj) {
        // Request headers
        xhrObj.setRequestHeader("Content-Type", "application/json");
        xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
      },
      type: "POST",
      // Request body
      data: '{"url": "https://philosophybank.files.wordpress.com/2013/08/happy-people.jpg"}',
    })
    .done(function(data) {
    JSON.stringify(data);
      alert(JSON.stringify(data));
      //console.log(data);
      //alert(data.scores);
    })
    .fail(function(error) {
      console.log(error.getAllResponseHeaders());

      alert("fail");
    });
});

</script>

此代码工作正常,但是我希望在我的网站上实现这一点,以便人们使用浏览按钮从他们的机器本地上传图像,而不是使用链接查找图像。任何帮助将不胜感激!

4

1 回答 1

3

我将application/octet-stream其用作主体类型来模拟它,它允许您发布二进制对象(即图像本身),而不是图像的 url。Emotion API 文档详细说明了这是一种受支持的内容类型。

根据您的原始示例,我继续使用 JQuery。

您应该能够将整个示例复制并粘贴到 HTML 文件中,在它说的位置添加您的 Emotion API 密钥,my-key它就会工作

<html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>

<body>
    <input type="file" id="file" name="filename">
    <button id="btn">Click here</button>

    <script type="text/javascript">
        $('#btn').click(function () {

            var file = document.getElementById('file').files[0];

            $.ajax({
                    url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
                    beforeSend: function(xhrObj) {
                        // Request headers
                        xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
                        xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
                    },
                    type: "POST",
                    data: file,
                    processData: false
                })
                .done(function(data) {
                    JSON.stringify(data);
                    alert(JSON.stringify(data));
                })
                .fail(function(error) {
                    alert(error.getAllResponseHeaders());
                });
        });
    </script>
</body>

</html>
于 2016-02-25T13:36:07.300 回答