Home > database >  Broken file upload with React to AWS S3
Broken file upload with React to AWS S3

Time:05-29

I've already tried multiple code for uploading, from axios to fetch. But, it always end up with same result. Here's the simplest it get:

    const formData = new FormData();
    formData.append('file', ref)

    const response = await fetch(
      new Request(res.uploadSignedUrl, {
        method: 'PUT',
        body: formData,
        headers: new Headers({
          'Content-Type': ref.type,
        })
      })
    )

The code above is responding with status 200, but whenever I visit the image link of the uploaded image, it gives me a small white box image.

screenshot of small white box image

And when I remove the header at 2nd parameter object of request fetch, the Content-Type to be specific, the link of the uploaded image doesn't transfer me to a website or anything. It just automatically downloads an unknown file type with surprisingly the exact file size of the supposed to be uploaded image.

screenshot of automatic download

Do note that I've already tried this with multiple file types. Any given thoughts about this issue will be deeply appreciated.

Edit: Also, I managed to come in contact with our backend dev. Here's the result at postman I think: screenshot of payload result

ANSWER: I commented it here

CodePudding user response:

If you are trying to send image to you backend guy , and then he is gonna upload it to AWS Bucket , then try to send image as base64, then he is able to do whatever he needs with that.

sample code to make base64 from image

const canvas = document.createElement('canvas')
const c = canvas.getContext('2d')

canvas.height = image.height
canvas.width = image.height

c.drawImage(image, 0, 0, canvas.width, canvas.height)

const base64 = canvas.toDataUrl('image/png' , 1.0)

CodePudding user response:

ANSWER:

from reddit user u/Wombarly,

You're uploading the form data instead of the actual image. So you have to get the image blob and upload it instead.

The form data adds the WebkitDisposition bit at the top of the payload in the screenshot. when you PUT to S3 that gets included in the file. corrupting it.

Here is an article I found that explains how:

https://medium.com/geekculture/upload-images-to-aws-s3-using-presigned-url-in-react-native-45059fe3d31b

You can ignore the react native bit

Additional note from this question's author:

I never knew WebkitDisposition at the payload causes the file to be corrupt for AWS S3. So I had to add another function to emit the file Uri and continue with u/Wombarly's suggestion. Wherein I use the code here: https://stackoverflow.com/a/50719098/18373031 by Srijita for reference. (The uri variable at _handleImageChange function)

  • Related