gpt4 book ai didi

javascript - Node/乘法器|无法根据字段名获取 sperarte 文件名

转载 作者:行者123 更新时间:2023-12-03 01:13:52 25 4
gpt4 key购买 nike

我结合 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);

使用名称属性在我的 View 中定义的不同字段名称来选择在应用程序中处理的不同项目。

下面是我的代码

浏览次数 [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();
});

非常感谢您的帮助,谢谢!

最佳答案

标记中的输入元素必须包装在表单中(它们可能已经包装在表单元素中,但未显示在您的问题中)。您还应该设置表单的 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"}

关于javascript - Node/乘法器|无法根据字段名获取 sperarte 文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com