0

I'm making an app which consumes an API I wrote, thing is that, I need the client to send an image to the API and then save it server-side, I successfully sent an image using a file input and the following script:

      const upload = _ => {
        let form = new FormData();
        form.append("file", document.getElementById("my-file-selector").files[0])
        fetch('http://localhost:3377/me/uploadPfp', {
          method: 'POST',
          headers: {
              "Authorization": "<%= locals.user.token %>",
              "Content-Type": "application/x-www-form-urlencoded"
          },
          body: form,
          }).then(
            response => response.json()
          ).then(
            success => console.log(success)
          ).catch(
            error => console.log(error)
          );
      };

Server-side it seems to work, but I'm unable to save it using fs.writeFile(), it returns this error:

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.

But when I console.log the received file, this happens: Receipt Image

Ulises Viña
  • 17
  • 1
  • 5

2 Answers2

0

"Content-Type": "application/x-www-form-urlencoded"

You aren't sending URL encoded data, so don't claim you are.

fetch can infer the correct content-type from the FormData object you pass it.

Your server-side code is believing your content type and misinterpreting the data.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I decided to use that header considering this post's comments and answers: https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api – Ulises Viña Apr 19 '21 at 17:29
  • @UlisesViña — Believe all the answers telling you not to do that over the one wrong comment that says you should. – Quentin Apr 19 '21 at 17:31
  • You were right. I'll mark your answer because you it's correct (though a bit rude). Thanks! – Ulises Viña Apr 19 '21 at 17:43
0

This seems that you are using the image file, instead, use this piece of code inside if statement

**fs.writeFile('file.txt', img.toString(), err){
  if (err) throw err;
  console.log('The file has been saved!');
}**

This piece of code converts & stores your image into a string.