Search code examples
node.jsexpressmulter

Multer's req.body works but req.files gives undefined


I'm trying to submit a form , that consists some text and an image file to the server. Regarding multer, my understanding is that, multer creates a storage folder for our images 'my-uploads/' and we pass on the key from formData.append('imageFile', imageFile) to upload.single('imageFile'). I tried giving paths like: my-uploads/, /my-uploads, ./my-uploads, so far none of it is working.

Next, using Fetch, I have been able to send the text body to the server and it reaches in [Object: null prototype].....(Not sure if it the right way of sending). The image files is not showing up the way expected too. Multer throws undefined when called req.files. Where is it going wrong with the code?

html:

   <form class="blogForm" method="post" encType="multipart/form-data">
     <input type="file" class="imageInput" name="file" multiple = "true"/>
    <div class="blogEntryDiv" contenteditable="true"></div>
    <input class= "blogSubmitButton" type="submit" value="Submit" >
  </form>

js

   document.querySelector('.blogForm').addEventListener('submit', (e) => {

      let formData = new FormData();
      let textContent = document.querySelector('.blogEntryDiv').innerText
      let imageFile = document.querySelector('.imageInput').files
      formData.append('textcontent', textContent);
      formData.append('imageFile', imageFile);
      
      fetch(`/someimage`, {
            method: 'POST',
            body: formData
          }).then(function (res){ 
            console.log(res);
          }).then(json => console.log(json))
          .catch(err => console.log(err));

   })

app.js:

 const multer  = require('multer');


 const storage = multer.diskStorage({
    destination: function (req, file, cb) {
       cb(null, 'my-uploads/')
    },
    filename: function (req, file, cb) {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
      cb(null, file.fieldname + '-' + uniqueSuffix)
    }
  })

 const upload = multer({ storage: storage })



 app.post('/someimage', upload.single('imageFile'),  (req, resp) => {
    console.log(req.body)
    console.log(req.files)//gives undefined
 })

req.body gives:

  [Object: null prototype] {
    textcontent: '\n\nlorem lorem',
    imageFile: '[object FileList]' //gives a string
   }

Solution

  • formData.append('imageFile', imageFile) does not work, because imageFile is a file list, but you can only append single files. Use formData.append('imageFile', imageFile[0]).

    Also, multer will write the single file into req.file, not into req.files.