javascript - React axios 多文件上传
问题描述
我正在尝试在 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)
})
解决方案
这是一个完整的工作设置(上面答案的扩展版本)
客户端:
// silly note but make sure you're constructing files for these (if you're recording audio or video yourself)
// if you send it something other than file it will fail silently with this set-up
let arrayOfYourFiles=[image, audio, video]
// create formData object
const formData = new FormData();
arrayOfYourFiles.forEach(file=>{
formData.append("arrayOfFilesName", file);
});
axios({
method: "POST",
url: serverUrl + "/multiplefiles",
data: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
//some error handling
服务器端(express、node - mutler)
const UPLOAD_FILES_DIR = "./uploads";
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, UPLOAD_FILES_DIR);
},
// in case you want to change the names of your files)
filename(req, file = {}, cb) {
file.mimetype = "audio/webm";
// console.log(req)
const {originalname} = file;
const fileExtension = (originalname.match(/\.+[\S]+$/) || [])[0];
cb(null, `${file.fieldname}${Date.now()}${fileExtension}`);
}
});
const upload = multer({storage});
// post route that will be hit by your client (the name of the array has to match)
app.post("/multiplefiles", upload.array('arrayOfFilesName', 5), function (req, res) {
console.log(req.files, 'files')
//logs 3 files that have been sent from the client
}
推荐阅读
- javascript - 事件委托/使用 Vanilla JavaScript 将事件附加到动态创建的元素
- python - 如何将网站上所有抓取的数据保存在 pandas 数据框中?
- javascript - Angular 7开始日期>结束日期验证
- google-chrome - 为什么扩展添加的搜索引擎在弹出菜单中不显示“设为默认”?
- php - 超时作业挂起 15 或 30 分钟,然后运行
- javascript - 如何使用 javascript/jquery 在打印页面上设置 div 内容的样式?
- java - Android是一个线程可以处理多个socket吗?
- c# - 对象的属性是否设置?
- java - Android:FileProvider.getUriForFile“找不到配置的根”
- sas - 如何将PROC FCMP(SAS)中SOLVE函数的输出分配给全局变量/表?