【发布时间】:2019-08-02 21:27:28
【问题描述】:
我有一个应用程序,在该应用程序中,我想使用一些文件上传机制。
我的要求是:
文件上传后,其名称将更改为唯一名称,例如 uuid4()。稍后我会将这个名称存储在数据库中。
我已经写了类似的东西,但是我有几个问题:
const multer = require('multer');
const upload = multer();
router.post('/', middleware.checkToken, upload.single('file'), (req,res,next)=>{
// key:
// file : "Insert File Here"
console.log("req:");
console.log(req.file);
const str = req.file.originalname
var filename = str.substring(0,str.lastIndexOf('.'));
// I will use filename and uuid for storing it in the database
// I will generate unique uuid for the document and store the document
// with that name
var extension = str.substring(str.lastIndexOf('.') + 1, str.length);
// HERE!
res.status(200).json();
})
我见过将它存储在 diskStorage 中的示例:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
但是,据我了解,这是 API 调用之外的配置。这意味着我每次调用此 API 时都无法修改它。我想为文件分配不同的名称,我需要该名称(uuid)将该名称保存在数据库中。
我怎样才能保留这样的功能?
【问题讨论】:
-
每次上传文件时都会调用
filename,因此您会得到不同的标识符。然后,新名称应该可以在req.file -
@Rashomon,所以,如果我将名称表示为 uuid,我可以通过 API 调用
req.file.fieldname? 获得此名称 -
我面前有一个工作示例,它存储在一个名为
filenameyes 的属性中。它不完全一样,因为我使用多上传