嗨,我正在上载图片。我遵循文档中的所有内容都可以正常工作,但我只是想使函数更具动态性。
首先我有我的控制器
async function store (req, res) {
const imgName = 'imgName';
upload(req, res, imgName, (err) => {
if (err) {
res.send('eror');
} else {
console.log(req.file);
res.send('test');
}
})
}
在上传功能中,我创建了新文件,名称为helpers.js
// Here i setup path and files name
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); }
})
// the problem are here imgName not define How can I pass variable into const upload
const upload = multer(imgName,{
storage: storage
}).single(imgName');
module.exports = {
upload,
};
答案 0 :(得分:0)
尝试导出函数upload
而不是预构建的对象:
const upload = imgName => multer(imgName, { storage: storage }).single(imgName);
module.exports = { upload }
然后,通过调用带有imgName参数的函数来使用控制器
async function store (req, res) {
const imgName = 'imgName';
upload(imgName)(req, res, imgName, (err) => {
if (err) {
res.send('eror');
} else {
console.log(req.file);
res.send('test');
}
})
}