为什么 Express Multer 要求输入字段名称与传递给中间件的字符串相同?

Why does Express Multer require the input field name be the same as the string that's passed to the middleware?

来自documentation
前端

<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>

后端:

var upload = multer({ dest: 'uploads/' })
 app.post('/profile', upload.single('avatar'), function (req, res, next) {
      // req.file is the `avatar` file
      // req.body will hold the text fields, if there were any
    })

我之前用Multer成功实现了文件上传。但是,现在我遇到了一个问题,我要发送一个包含一些信息的对象以及文件,而不仅仅是文件。所以我一直在努力理解这是怎么回事:

upload.single('avatar')

有效。而且网上似乎没有任何解释,除了传递的字符串必须与字段输入名称相同,如果有的话,会使整个事情更加混乱。

假设您有一个包含 3 个字段的表单:

  • 姓名(文字)
  • 电子邮件(文本)
  • 照片(文件)

当以 json 格式发送此表单时,Nodejs 将收到如下数据:

"{"name": "value", "email": "value", "photo": "[binary]"}"

到目前为止一切顺利。这里multer很容易知道要解析的字段是"photo".

现在想象一下,由于某些原因,您的后端要求您在发送表单之前将所有输入值解析为二进制。现在您必须转换您的输入表单并发送如下:

"{"name": "[binary]", "email": "[binary]", "photo": "[binary]"}"

穆尔特:"Okay, I have 3 binary fields, which one should I convert to file ?"