node.js - Multer: upload different file types in different folders
问题描述
I have a simple form with two file input fields. One is about an image, and the other is about a mp3 file.
I have an express server which utilizes multer as file upload system. I'd like to save the image inside the img
, and the mp3 file inside the music
folder.
This is what I tried so far:
var musicUpload = multer({dest: 'music'});
var imgUpload = multer({dest: 'img'});
app.post('music',
musicUpload.single('music'),
imgUpload.single('img'),
function (req, res) {
...
});
While this is the form:
<form action="post" enctype="multipart/form-data" action="music">
<input type="file" id="img" name="img">
<input type="file" id="music" name="music">
<input type="submit" value="Send">
</form>
I need to handle the 2 different files in a different way, this is the reason why I used "single" twice. But, unluckly, I receive a "Unexpected field" error message.
How can achieve the result?
Ps. There are many question on SO about multiple files uploading, but none of them solved my specific problem. Don't be too much fast at flagging this question :)
解决方案
You could try using something like DiskStorage. As per their docs: https://github.com/expressjs/multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
if (file.mimetype === 'audio/mp3') {
cb(null, 'songs')
} else if (file.mimetype === 'image/jpeg') {
cb(null, 'img')
} else {
console.log(file.mimetype)
cb({ error: 'Mime type not supported' })
}
}
})
var upload = multer({ storage: storage })
and then on the endpoints themselves do:
var upload = multer({storage});
router.post('/song', upload.any(), function(req, res) {
...
});
this is probably cleaner then your approach and i think gives the functionality you're looking for as it gives you more granular control over saving those files. (with edits by @cristian)
推荐阅读
- css - 如何在圆圈内创建 + 并更改为 - 仅使用 CSS 悬停
- javascript - 我很困惑是否应该使用 URL 路径参数或查询参数在后端进行过滤?
- c++ - 如何让openCV solvepnp头部姿态估计输出更准确
- flutter - 将日期时间从上午更改为下午
- python - 刽子手游戏在整个游戏中改变单词
- c++ - 每个模板实例化的 GCC/Clang 函数属性
- javascript - 使用 puppeteer 的 browser.newPage() 时 Firebase 函数超时
- cors - Aurelia:为 API 调用配置代理路径
- arrays - 取消引用 3 维数组
- numpy - 将函数应用于没有循环的嵌套 numpy 数组