How to store a file with file extension with multer? How to store a file with file extension with multer? express express

How to store a file with file extension with multer?


I have a workaround for the adding proper extension of files. If you use path node module

var multer = require('multer');var path = require('path')var storage = multer.diskStorage({  destination: function (req, file, cb) {    cb(null, 'uploads/')  },  filename: function (req, file, cb) {    cb(null, Date.now() + path.extname(file.originalname)) //Appending extension  }})var upload = multer({ storage: storage });


From the docs: "Multer will not append any file extension for you, your function should return a filename complete with an file extension."

Here's how you can add the extension:

var multer = require('multer');var storage = multer.diskStorage({  destination: function (req, file, cb) {    cb(null, 'uploads/')  },  filename: function (req, file, cb) {    cb(null, Date.now() + '.jpg') //Appending .jpg  }})var upload = multer({ storage: storage });

I would recommend using the mimetype property to determine the extension. For example:

filename: function (req, file, cb) {  console.log(file.mimetype); //Will return something like: image/jpeg

More info: https://github.com/expressjs/multer


I got file the extension from file.mimetype .I split the mimetype and get the file extension from itPlease try the below function.

let storage = multer.diskStorage({  destination: function (req, file, cb) {    cb(null, './uploads')  },  filename: function (req, file, cb) {    let extArray = file.mimetype.split("/");    let extension = extArray[extArray.length - 1];    cb(null, file.fieldname + '-' + Date.now()+ '.' +extension)  }})const upload = multer({ storage: storage })