gpt4 book ai didi

node.js - 多自定义文件名 req.body.inputTextField 作为文件名

转载 作者:搜寻专家 更新时间:2023-11-01 00:50:37 25 4
gpt4 key购买 nike

我不知道如何使用 req.body.fname 作为文件名,甚至尝试使用中间件,但 req.body 是空的。

var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, req.body.fname) // undefined
}
})
var upload = multer({ storage: storage })

app.get('/upload', upload.single('fname'), (req,res)=>{
.......
})

i m unable to figure out how to fetch fname in fileName
index.html

<form action="/upload" method="POST" enctype= "multipart/form-data">
<input type="text" name="fname">
<input type="file" name="pic">
<input type = "submit">
</form>

最佳答案

这不是一种优雅的方式,但总比没有好。


multer 不能做什么


据我所知,Multer 仅在实际文件发送后才发送 req.body 字段。因此,当您命名文件时,您将无权访问这些字段。由于 enctype 设置为 multipart,Body Parser 也将停止工作。

从哪里获取req.body


虽然晚了,但 Multer 毕竟确实发送了 req.body 字段。这些将在上传文件后访问:

app.post('/upload', (req, res) => {
upload(req, res, function (err) {
console.log(req.body.fname) // Here it works
});
});


一个简单的解决方法


现在我们上传图片后,我们有一个名为“undefined”的文件,(顺便说一句,你可能想添加扩展名,我稍后会讲到。)我们可以通过 req.file.path 访问它的路径。所以现在我们调用 fs 来重命名它。它是 Node.js 原生的,因此无需安装。只需在使用前要求它:

const fs = require('fs');

然后我们回到上传过程。

app.post('/upload', (req, res) => {
upload(req, res, function (err) {
fs.renameSync(req.files.path, req.files.path.replace('undefined', req.body.fname));
// This get the file and replace "undefined" with the req.body field.
});
});

我假设您的文件路径没有名为“undefined”的文件夹。在这种不太可能发生的情况下,只需将文件命名为 Multer 并稍后将其替换为 fs.renameSync。


最后一点:添加扩展


如果您不打算在 HTML 输入字段中输入扩展名,您可能希望在命名过程中附加扩展名。要获得扩展,我们可以使用路径,它也是 Node.js 原生的,只需要是必需的:

const path = require('path');

var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, req.body.fname + path.extname(file.originalname))
}
})

或者在不太可能的情况下,您需要“.undefined”扩展名,只需稍后在 fs 重命名过程中附加扩展名即可。

希望这能解决您的问题。编码愉快!

关于node.js - 多自定义文件名 req.body.inputTextField 作为文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131922/

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