【发布时间】:2019-04-28 10:41:53
【问题描述】:
我知道我可以使用 multer 通过存储对象更改文件名,如下所示:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, process.env.UPLOAD_DIR);
},
filename: (req, file, cb) => {
cb(null, 'bla.png');
}
});
const upload = multer({ storage: storage } );
我的请求,除了有文件外,还包含一些文字属性如name: myPic.png。
是否可以根据其他请求属性或在控制器内动态更改文件名,如下所示:
filename: (req, file, cb) => {
cb(null, `${req.body.name}.png`);
}
或
router.post('/upload', upload.single('pic'), myController.upload);
/* in controller */
upload = async (req: Request, res: Response) => {
try {
/* change the filename of multer here? */
} catch (err) {
winston.error(`Error while uploading: ${err.message}`);
winston.error(`Stack trace: ${err.stack}`);
sendJSONResponse(res, err, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
【问题讨论】:
-
我遇到了同样的问题,你找到解决办法了吗?
标签: javascript node.js file-upload multer