【发布时间】:2019-02-17 18:25:04
【问题描述】:
我正在尝试使用 react 应用添加多个图像并将它们发送到后端代码以将它们存储在 mongodb 中
这是后端的代码: link
这是前端link
所以这段代码只适用于一张图片
我需要能够添加多个图像
【问题讨论】:
我正在尝试使用 react 应用添加多个图像并将它们发送到后端代码以将它们存储在 mongodb 中
这是后端的代码: link
这是前端link
所以这段代码只适用于一张图片
我需要能够添加多个图像
【问题讨论】:
由于您使用的是multer,请将upload.single() function 更改为upload.array()。
例如:
app.post("/addItem",
upload.array('product-image', 4), // 'product-image' is field name and 4 is the max number of files allowed
(req, res) => {
console.log(req.files);
// ... rest of the logic
}
)
Change current <input> 允许多个文件:
<input type="file" name="product-image" onChange={this.fileChangeHandler} multiple>
现在保存用户选择的所有图像not only the event.target.files[0]:
fileChangeHandler(event) {
let files = event.target.files
this.setState({ selectedFiles: files })
}
现在add them in FormData 照常上传:
let formData = new FormData()
formData.append("product-image", this.state.selectedFiles)
就是这样!希望对您有所帮助。
PS:我认为不应该将文件添加到状态中。您可以简单地将它们添加到类变量中。在this answer 中,我解释了为什么以及如何做到这一点。
更新:
您现在需要遍历文件。您的/addItem 端点的代码将如下所示:
app.post("/addItem", upload.array('product-image', 4), (req, res) => {
console.log(req.files);
let paths = [];
req.files.forEach(file => {
console.log("new file location", file.path)
let extension = file.originalname.split(".").pop()
fs.rename(file.path, file.path + "." + extension, () => {})
paths.push("/" + file.filename + "." + extension);
});
console.log("body", req.body)
let itemToStore = {
paths: paths, // notice this `paths` now, it was `path`
description: req.body.description
}
console.log("we are adding", itemToStore)
itemData.push(itemToStore)
console.log("updated itemData:", itemData)
res.send(JSON.stringify(itemData))
})
我没有修改您的代码,只是添加了一个循环。您的 'path' of undefined 错误应该会消失。
【讨论】: