How to store a file with file extension with multer?

Managed to store my files in a folder but they store without the file extension.

Does any one know how would I store the file with file extension?


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 it Please 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 })

It can be done like this:

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, config.DIR)
    },
    filename: function (req, file, cb) {
        let ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
        cb(null, Date.now() + ext)
    }
});
const upload = multer({
    storage: storage
}).any();