我如何让multer接受来自多个文件类型字段的文件?
我有以下代码,使用node.js中的multer上传单个文件:
var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, './public/uploads'); }, filename: function (req, file, callback) { callback(null, file.fieldname + '-' + Date.now()); } }); var upload = multer({ storage : storage }); app.post('/rest/upload', upload.array('video', 1), function(req, res, next){ ... }
通过以下形式,在仅视频字段具有值的条件下(如果同时指定两个字段,则会出现“意外字段”错误):
<form action="/rest/upload" method="post" enctype="multipart/form-data"> <label>Video file: </label> <input type="file" name="video"/> <label>Subtitles file: </label> <input type="file" name="subtitles"/> <input type="submit"/> </form>
从文档中不清楚该如何处理?任何建议,将不胜感激。顺便说一句,我尝试了以下参数变体,但没有成功:
app.post('/rest/upload', [upload.array('video', 1), upload.array('subtitles', 1)] ... app.post('/rest/upload', upload.array('video', 1), upload.array('subtitles', 1), ... app.post('/rest/upload', upload.array(['video', 'subtitles'], 1), ...
您想要的是upload.fields():
upload.fields()
app.post('/rest/upload', upload.fields([{ name: 'video', maxCount: 1 }, { name: 'subtitles', maxCount: 1 }]), function(req, res, next){ // ... }