使用imgur Mashape API在javascript中上传图片

时间:2016-03-29 20:42:33

标签: javascript imgur mashape

我正在尝试构建一个非常简单的后台图像上传器。我使用以下代码段使用Imgur Mashape API上传图像。但我一直收到错误: {"data":{"error":"Image format not supported, or image is corrupt.","request":"\/3\/image","method":"POST"},"success":false,"status":400}。当我在Mashape上测试Endpoint时,一切正常,并且之前只使用Imgur API成功使用了相同的功能。我觉得我错过了一些东西但是尽管经过研究我找不到合适的解决方案。我应该如何处理以便能够使用纯JavaScript中的Mashape Imgur API上传图像?

var uploadImg = function( file ) {
        if (!file || !file.type.match(/image.*/)) return;

        var fd = new FormData();
        fd.append("image", file);

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "https://imgur-apiv3.p.mashape.com/3/image");
        xhr.onload = function() {
            console.log(xhr.responseText);
        }

        xhr.setRequestHeader('Authorization', 'Client-ID my_Client-Id');
        xhr.setRequestHeader('X-Mashape-Key', 'My_MASHAPE_Key');
        xhr.setRequestHeader('Content-Type', 'multipart/form-data');
        xhr.send(fd);
    }

1 个答案:

答案 0 :(得分:0)

我从我见过的示例中尝试了Content-Type标题的不同值。以下都不起作用:application/jsonapplication/x-www-form-urlencodedmultipart/form-data。但完全删除标题的此属性的规范使一切正常。

因此,如果有人遇到同样的问题,只需删除我设置Content-Type的行,您就可以了。