runtimeZero
runtimeZero

Reputation: 28086

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
router.post('/auth/signup/upload', upload.single('image'), function(req, res) {
  console.log(req.body.username); // contains value
  res.send(); 
});

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

Upvotes: 0

Views: 454

Answers (1)

slugonamission
slugonamission

Reputation: 9642

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 http://foo.bar?username=me). You could also manually move the file afterwards, or store the mappings between usernames and files elsewhere.

Upvotes: 1

Related Questions