Node / Multer |无法根据fieldname获取sperarte文件名

问题描述 投票:0回答:1

我与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();
});

非常感谢帮助,谢谢!

javascript node.js node-modules multer
1个回答
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"}
© www.soinside.com 2019 - 2024. All rights reserved.