Search code examples
javascriptimgurmashape

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. 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}. 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. 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 ?

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

Solution

  • I tried different values for the Content-Type header from examples that I have seen around. None of the following worked: application/json, application/x-www-form-urlencoded, multipart/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.