Skip to content
Advertisement

How to rename file in Multer middleware to data I am sending in request

On a frontend I am generating unique ID for every order. Idea is to rename file which user uploads to orderId. Here is my request to server:

   const handleFileUpload = e => {
      const formData = new FormData()
      formData.append("pdf-file", e.target.files[0])
      formData.append("orderId", orderId)

      axios.post("http://localhost:8000/upload", formData, { headers: { "Content-Type": "multipart/form-data" } })
         .then(res => {
            console.log(res)
         })
         .catch(error => {
            console.log(error)
         })
   }

Here is the server code:

const storage = multer.diskStorage({
   destination: (req, file, cb) => {
      cb(null, "./uploads")
   },
   filename: (req, file, cb) => {
      console.log(req.body)
      cb(null, `${file.fieldname}-${req.body.orderId}`)
   }
})

const uploadStorage = multer({storage: storage})

app.post("/upload", uploadStorage.single("pdf-file"), (req, res) => {
   console.log(req.body)
   return res.send("file upload")
})

console.log(req.body) shows empty object in filename and orderId in app.post(). Here is how it looks:

[Object: null prototype] {} // inside filename
[Object: null prototype] { orderId: 'e923920b-fdf0-41ab-97dd-2fcf20b57250' } // inside app.post()

So this cannot be done as far as I understand inside filename. How to deal with this situation? And is this even possible?

Answer

All I had to do, is to change order I am appending to formData.

Now this works:

formData.append("orderId", orderId)
formData.append("pdf-file", e.target.files[0])
Advertisement