Allen
Allen

Reputation: 3771

Multer: how to name files after req.body parameters

I'm trying to upload a file with a form such as below

<input type="file" name="collateral" />
<input type="hidden" name="id" value="ABCDEFG" />
<input type="submit" value="Upload Image" name="submit">

and I would like to rename to file to the name in the id input (ABCDEFG). As I can't access the req.body through the rename: function(fieldname, filename), I was wondering how I would achieve this?

Upvotes: 3

Views: 1887

Answers (1)

Lev
Lev

Reputation: 15694

Try putting the file last in your POST request payload.

Then you should be able to access req.body via this callback:

var multer  = require('multer');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
        // access req.body and rename file 
    }
});

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

Upvotes: 1

Related Questions