简体   繁体   中英

Bad request status 400 when trying to upload image file to imgur

I'm trying upload image file from my React app. Keep getting 400 error, witch I can't understand why. That's my TypeScript function's code in React:

   public setImage = (args: ChangeEvent<HTMLInputElement>) => {

        const image = args.target.files[0];
        let formData: FormData = new FormData();
        formData.append("profileImage", image, image.name);
        const requestOptions = {
            method: 'POST',
            headers: { 'Authorization': 'Client-ID //my client-id here//' },
            image: image
        };
        fetch('https://api.imgur.com/3/image', requestOptions)
            .then(response => response.json())
            .then(data => console.log(data));

    }

And the error:

{
data: error: "No image data was sent to the upload api"
method: "POST"request: "/3/image"
__proto__: Objectstatus: 400
success: false
__proto__: Object
}

When i'm trying to console my FormData object after appending I can see an empty object. Thanks for any answer!

The first thing that comes to mind is to log the image object as well and see if there are any problems there.

Also please take a look at this to verify that you're logging your FormData object correctly.

If however, this is still not enough to debug the issue, I would advise you to try rolling a request using something like curl or Fiddler since you are manually creating the POST headers. Because of this, you're not sending the Content-Length header which could cause the imgur api to just skip the whole body of your request.

To get the content lenght you could do something like:

    let content-length = JSON.stringify(formData).length;

     
    

Then simply:

const requestOptions = {
        method: 'POST',
        headers: { 'Authorization': 'Client-ID //my client-id here//', 'Content-Length': content-length },
        image: image
    };

Hope this is useful in some way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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