multer自定义文件名req.body.inputTextField作为文件名

时间:2018-09-01 20:26:29

标签: node.js multer multifile-uploader

我无法弄清楚如何使用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>

1 个答案:

答案 0 :(得分:2)

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


行不通的人


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

您在哪里可以得到身体


尽管很晚,但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重命名过程中附加该扩展名即可。

希望这可以解决您的问题。祝您编程愉快!

相关问题