我结合multer创建了一个Express应用,以将项目上传到我的Node.js应用中
我要选择的是选择:
Upload 1 - that has a fieldname of upfile1
Upload 2 - that has a fieldname of upfile2
Upload 3 - that has a fieldname of upfile3
基本上,我需要分别选择多上传应用程序的每个上传文件名项目。对于不同的任务,需要在应用程序中对每个上传进行不同的处理。让我们以console.log为例,我需要做以下事情:
console.log(req.body.upfile1.filename);
console.log(req.body.upfile2.filename);
console.log(req.body.upfile3.filename);
通过使用name属性在我的视图中定义的不同字段名来选择应用程序要处理的不同项目。
下面是我的代码
查看[index.html]
<form id="app-form" method="POST" class="fileupload" method="post" action="app" enctype="multipart/form-data">
<h1>Multi File Uploads</h1>
<input type="file" name="upfile1" value="">
<input type="file" name="upfile2" value="">
<input type="file" name="upfile3" value="">
<input type="submit" />
</form>
NodeJS [app.js]
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/app", upload.any(), function(req, res) {
let files = req.files;
files.forEach(file => {
console.log(file.filename);
});
res.send(req.files);
res.end();
});
非常感谢您的帮助!
答案 0 :(得分:1)
标记中的输入元素必须包装在表单中(它们可能已经包装在表单元素中,但未在问题中显示)。您还应该设置表单的enctype attribute to multipart/form-data。
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="upfile1">
<input type="file" name="upfile2">
<input type="file" name="upfile3">
<input type="submit" value="Submit">
</form>
完成后,您可以配置multer并创建处理文件上传的路径:
const upload = multer({
dest: path.join(__dirname, './upload') // You might want to change this according to your preferences
// Since you're using any(), you might want to set fileFilter to control which files should be uploaded. See: https://github.com/expressjs/multer#filefilter
});
const findFileByFieldname = (files, fieldname) => {
return files.find(file => file.fieldname === fieldname) || {};
}
app.post("/upload", upload.any(), (req, res) => {
const upfile1Filename = findFileByFieldname(req.files, 'upfile1').filename;
const upfile2Filename = findFileByFieldname(req.files, 'upfile2').filename;
const upfile3Filename = findFileByFieldname(req.files, 'upfile3').filename;
res.json({
upfile1Filename,
upfile2Filename,
upfile3Filename,
});
});
// Example response (Node v8.11.4, Express v4.16.3, Multer v1.3.1)
// {"upfile1Filename":"360726b532a01b0e31832f067b5922c8","upfile2Filename":"144e1298437afb51f36eb37c77814650","upfile3Filename":"4c908da20e770130377e4006db945af6"}