Search code examples
node.jsexpressfetch-api

How to read the contents of a "file" object (not local file) in express?


i want to save user input including file input and post that object using fetch, like this:

// ...
subBtn.addEventListener('click', requestCreate);

async function requestCreate(e) {

  e.preventDefault();

  try {

    const obj = {

      method: "POST",

      headers: { 'Content-Type': 'application/json' },

      body: `{"title": "${name.value}", "body": "${email.value}", "file": ${file.files[0]}, "file2": ${file.files[1]}}`
    }

    const res = await fetch('http://localhost:3000/', obj);

    if (!res.ok) throw Error(res.statusText);

  } catch (error) { console.log(error) }
}

But i can't access the file in the backend

app.post('/', (req, res)=> {

  console.log(req.body.file) // returns [object File]
  res.send({name: 'hello world'});
})

app.use(express.json())

I've googled whole day but found nothing that helps. i feel like iam using fetch wrong way to upload files

can somebody plz explain, if i can upload files to backend without using formData object ? is it not recommended ?


Solution

  • select a single using HTML5

    <label>
      img: <input accept="text/*" type="file"/>
    </label>
    

    upload a single file using fetch

    const input = document.querySelector(`input[type="file"]`);
    
    function upload() {
      fetch(uplaodURL, { method: "POST", body: input.files[0] });
    }
    
    input.addEventListener("change", upload); 
    

    access a single file in express

    app.post('/', express.raw({ inflate: true, limit: '50mb', type: () => true }), async (req, res) => {
      
      console.log("=>", req.body.toString()) // accessing the text file
      res.json({ bodySize: req.body.length });
    });
    

    Note: as mentioned by "Gabriel Freitas Yamamoto" in the comment, you can access the input file by inputElement.files, but you can't actually send it with other input fields using json. sending file.files[0] object will be turned into a string "[object File]".

    so you would either need to convert your file to base64 string and send it as string or send the file (including other fields) as multipart formData