且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用multer存储具有文件扩展名的文件?

更新时间:2022-11-28 07:56:20

来自文档:Multer 不会为您附加任何文件扩展名,您的函数应该返回一个带有文件扩展名的文件名."

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 });

我建议使用 mimetype 属性来确定扩展名.例如:

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

更多信息:https://github.com/expressjs/multer