【发布时间】:2020-02-11 09:15:57
【问题描述】:
我正在尝试在 React 中使用 axios 上传多个图像,但我不知道出了什么问题。首先,我尝试上传单个图像,并且效果很好。但是对于多张图片,我别无选择。
我正在像这样创建 FormData:
for (let i = 0; i < images.length; i++) {
formData.append('productPhotos[' + i + ']', images[i]);
}
axios 请求是这样的
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios
.post(endPoints.createProduct, formData, config)
.then(res => console.log(res))
.catch(err => console.log(err));
我的后端是 node/express,我正在使用 multer 进行上传。签名是这样的:
app.post("/product", upload.array("productPhotos"), (req, res) => {
我在 PostMan 中尝试了这个后端端点并且上传工作正常,所以错误必须在前端。感谢您的帮助。
更新 在formData中传递多个文件的正确方法:
images.forEach(img => {
formData.append("productPhotos", img)
})
【问题讨论】:
-
什么是
images? -
图像选择器中的文件数组。
-
感谢您的回答。我使用的是 FileList 对象而不是 File 对象。但是你的回答让我想到了,谢谢:)
标签: javascript node.js reactjs express axios