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

Upload image with Imgur Mashape API in javascript

我正在尝试构建一个非常简单的后台图像上传器。我正在使用以下代码片段通过 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 上成功使用了相同的功能。我觉得我错过了一些东西,但尽管进行了研究,我还是找不到合适的解决方案。我应该如何进行才能使用 Mashape Imgur API 纯 javascript 上传图像?

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);
    }

我从周围看到的示例中尝试了 Content-Type header 的不同值。以下 None 个有效:application/jsonapplication/x-www-form-urlencodedmultipart/form-data。但是完全删除 header 的这个属性的规范使一切正常。

因此,如果有人遇到同样的问题,只需删除我设置 Content-Type 的那一行,你应该没问题。