【发布时间】:2021-05-24 17:23:27
【问题描述】:
我正在开发一个 NodeJS/Express 应用程序,我必须在用户输入后提交表单。
可能有一个或一百万个input type text 字段,这取决于用户。每个文本字段都有自己的input type file,允许用户选择上传文件。
假设用户决定提交 3 条数据,因此他选择了 3 个文本字段:textField1, textFieldd2, and textField3。这些文本字段中的每一个都有自己的文件上传字段:fileFieldFortext1, fileFieldFortext2, and fileFieldFortext3。现在,他是上传文件还是将其留空,完全取决于他。
场景 1:当他决定为所有 3 个文本字段上传文件时:
<input type="text" name="textContent" />
<input type="file" name="fileInput" />
<input type="text" name="textContent" />
<input type="file" name="fileInput" />
<input type="text" name="textContent" />
<input type="file" name="fileInput" />
const textContent = req.body.textContent;
const fileData = req.files.fileInput;
textContent output: an array of all the texts. ['text1', 'text2', 'text3']
fileData output: an array of objects of all the file data. [ {'fileFortext1'}, {'fileFortext2'}, {'fileFortext3'} ]
我可以根据他们的index 轻松关联他们。它完美地工作。但问题出现在场景 2 中。
场景 2:当他决定不上传一两个文件时:
<input type="text" name="textContent" />
<input type="file" name="fileInput" /> // leaves it empty
<input type="text" name="textContent" />
<input type="file" name="fileInput" />
<input type="text" name="textContent" />
<input type="file" name="fileInput" />
const textContent = req.body.textContent;
const fileData = req.files.fileInput;
textContent output: an array of all the texts. ['text1', 'text2', 'text3']
fileData output: an array of objects of all the file data. [ {'fileFortext2'}, {'fileFortext3'} ].
现在我无法根据索引值关联它们,因为用户没有为第一个上传任何文件。
如何在我的后端得到这样的输出:[ {}, {'fileFortext2'}, {'fileFortext3'} ],第一个是空对象?
或
如何将每个文本字段与其自己的文件上传输入相关联?
我是否以错误的方式接近它?
请注意,我没有使用 AJAX 提交表单。这是直接提交。
【问题讨论】:
标签: javascript node.js express