This is not an elegant way, but it's better than nothing.
What multer can't do
As far as I know, Multer sends the req.body fields only after the actual file has been sent. So when you name the files, you won't have access to the fields. And as the enctype is set to multipart, Body Parser will cease to work as well.
Where can you get req.body
Although late, Multer actually sends the req.body fields after all. These will be accessible after uploading the files:
app.post('/upload', (req, res) => {
upload(req, res, function (err) {
console.log(req.body.fname) // Here it works
});
});
A simple work-around
Now after we upload the picture, we have a file named "undefined", (BTW you may want to add extension, I'll get to that later.) the path of which we can access through req.file.path. So now we call fs to rename it. It's native to Node.js so there is no need to install. Simply require it before use:
const fs = require('fs');
Then we go back to the uploading process.
app.post('/upload', (req, res) => {
upload(req, res, function (err) {
fs.renameSync(req.files.path, req.files.path.replace('undefined', req.body.fname));
// This get the file and replace "undefined" with the req.body field.
});
});
I'm assuming that your path to the file don't have a folder called "undefined". In this unlikely case, just name the file something else with Multer and replace that later with fs.renameSync.
Final touch: add extension
If you don't plan on entering extension in the HTML input field, you may want to attach the extension in the naming process. To get the extension, we can use path, which is also native to Node.js and only need to be required:
const path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, req.body.fname + path.extname(file.originalname))
}
})
Or in the unlikely case you want a ".undefined" extension, just attach the extension later in the fs renaming process.
Hope this solves your problem. Happy coding!