我知道我可以通过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 } );
除了文件之外,我的请求还包含一些文本属性,例如名称: 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);
}
}