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:
JavaScript
x
14
14
1
const handleFileUpload = e => {
2
const formData = new FormData()
3
formData.append("pdf-file", e.target.files[0])
4
formData.append("orderId", orderId)
5
6
axios.post("http://localhost:8000/upload", formData, { headers: { "Content-Type": "multipart/form-data" } })
7
.then(res => {
8
console.log(res)
9
})
10
.catch(error => {
11
console.log(error)
12
})
13
}
14
Here is the server code:
JavaScript
1
17
17
1
const storage = multer.diskStorage({
2
destination: (req, file, cb) => {
3
cb(null, "./uploads")
4
},
5
filename: (req, file, cb) => {
6
console.log(req.body)
7
cb(null, `${file.fieldname}-${req.body.orderId}`)
8
}
9
})
10
11
const uploadStorage = multer({storage: storage})
12
13
app.post("/upload", uploadStorage.single("pdf-file"), (req, res) => {
14
console.log(req.body)
15
return res.send("file upload")
16
})
17
console.log(req.body)
shows empty object in filename
and orderId in app.post()
.
Here is how it looks:
JavaScript
1
3
1
[Object: null prototype] {} // inside filename
2
[Object: null prototype] { orderId: 'e923920b-fdf0-41ab-97dd-2fcf20b57250' } // inside app.post()
3
So this cannot be done as far as I understand inside filename. How to deal with this situation? And is this even possible?
Advertisement
Answer
All I had to do, is to change order I am appending to formData.
Now this works:
JavaScript
1
3
1
formData.append("orderId", orderId)
2
formData.append("pdf-file", e.target.files[0])
3