runtimeZero runtimeZero - 2 months ago 47
Node.js Question

Renaming files using multer

I have configured multer as;

var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, '../images/profile');
filename: function(req, file, cb) {
cb(null, req.body.username + '.jpeg'); // file does not get renamed

var upload = multer({storage: storage});

// Route that uses multer'/auth/signup/upload', upload.single('image'), function(req, res) {
console.log(req.body.username); // contains value

Although req.body.username has a value, the file does not get renamed.
Wht am i missing here ?


From the multer manual:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

Sadly, I don't believe there's a nice way to solve this. You could try switching the order of the fields in your HTML form, but this probably won't lead to consistent behaviours across browsers. You could also send the username on the query string instead (i.e. POST the file to You could also manually move the file afterwards, or store the mappings between usernames and files elsewhere.