1

I want to know what the difference is between using the Fetch API and the Axios API specifically when making a PUT call to upload an image.

I spent the day trying different ways of sending the body (an image) of my fetch request to be uploaded to an S3 signed url, however the image uploaded to the S3 bucket kept showing the file to have 0 or 2 bytes.

When comparing the headers between both requests, I noticed the once difference was the Content-Length header. The Content-Length header value was 0 or 2 when using fetch and it was 477386 (depends on the size of the file) when using Axios.

  // Fetch
  const response = await api({
    url: signedURL,
    method: 'PUT',
    body: image,
    headers: {
      'Content-Type': image.type,
    },
  })

  // Axios
  const response = await axios.put(signedURL, image, {
    headers: {
      'Content-Type': image.type,
    },
  })

I've tried several different ways of sending the body using fetch such as using a FormData object, using a Blob to send the image, and even just sending the image file alone (as shown above). I've also tried using Postman to test my upload and it worked without an issue.

Is there something I'm missing when using fetch that I need to do in order to have the correct Content-Length header?

sbodi
  • 36
  • 5
  • Does this answer your question? [How do I upload a file with the JS fetch API?](https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api) – Keith Nicholas Dec 01 '20 at 22:31
  • personally I preffer fetch, because it is built in Javascript, and Axios is a dependecy, but I have used both with same results... – assembler Dec 01 '20 at 22:31
  • I personally prefer fetch as well for the same reason @assembler. However, in this case, fetch was not working. Axios worked. I don't understand why. – sbodi Dec 01 '20 at 22:34
  • @sbodi I would like to recomend you to use postman, you can use it to test your request and the most helpful thing is that it will give you the correct fetch, or axios, connection... try that. – assembler Dec 02 '20 at 13:30
  • @assembler Thanks! I also did try Postman and it worked. Just don't understand why fetch didn't work in the browser. – sbodi Dec 02 '20 at 15:01

1 Answers1

-1

You can use FormData() api in your fetch. You need to create a new FormData object and append it with file parameter which going to have your image file and you can send that as your body.

let body = new FormData();
body.append('file', image);
fetch(signedURL, { method: 'PUT', body: body });
Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
  • The URL appears to be expecting a PNG as the request body, not a multipart/form-data encoded body. – Quentin Dec 01 '20 at 22:46
  • Thanks for your response, however I tried this. I even tried using a Blob. FormData, Blob, nor even just sending the file itself worked. Once I switched to Axios, the file sent and S3 received without any corruption. – sbodi Dec 02 '20 at 13:17