简体   繁体   English

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

[英]Upload image with Imgur Mashape API in javascript

I'm trying to build a very simple back-office image uploader. 我正在尝试构建一个非常简单的后台图像上传器。 I am using the following snippet to upload images with the Imgur Mashape API. 我正在使用以下代码段通过Imgur Mashape API上传图像。 But I keep getting the error: {"data":{"error":"Image format not supported, or image is corrupt.","request":"\\/3\\/image","method":"POST"},"success":false,"status":400} . 但是我一直收到错误消息: {"data":{"error":"Image format not supported, or image is corrupt.","request":"\\/3\\/image","method":"POST"},"success":false,"status":400} Everything works just fine when I test the Endpoint on Mashape and also the same function was used successfully before with just the Imgur API. 当我在Mashape上测试端点时,一切工作都很好,并且仅使用Imgur API之前成功使用了相同的功能。 I feel like I am missing something but despite researching I could not find a suitable solution. 我觉得自己缺少了一些东西,但是尽管进行了研究,但找不到合适的解决方案。 How should I proceed in order to be able to upload an image with the Mashape Imgur API in pure javascript ? 如何才能使用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);
    }

I tried different values for the Content-Type header from examples that I have seen around. 我从周围的示例中尝试了不同的Content-Type标头值。 None of the following worked: application/json , application/x-www-form-urlencoded , multipart/form-data . 以下方法均无效: application/jsonapplication/x-www-form-urlencodedmultipart/form-data But completely removing the specification of this attribute of the header made everything work. 但是完全删除标头的此属性的说明使一切正常。

So if anyone runs in the same problem just remove the line where I set up the Content-Type and you should be fine. 因此,如果有人遇到相同的问题,只需删除我设置Content-Type的行,就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM