reactjs - 无法在 React 上使用 Multer 上传多个文件
问题描述
当我使用 Postman 上传多个图像时,Multer 工作正常,但是当我尝试从前端将文件作为数组发送时,它总是返回文件未定义且文件不可迭代。
我认为问题出在前端 React 中。如何解决这个问题?
后端
router.post('/multer',auth ,upload.array('image'), async (req, res) => { //NOTE image is the field name
try {
const urls = []
const files = req.files;
console.log('Upload cloudinary running '+ files)
.
.
.
前端反应
import React, {Fragment, useState, useEffect} from 'react';
const Dashboard = ({auth: { user, loading }}) => {
.
.
.
const [files, setFiles] = useState([]);
const handleChange = e => {
const file_reader = new FileReader();
const file = e.target.files[0];
let file = e.target.files[0];
file_reader.onload = () => {
setFiles([...files, { image: file_reader.result }]);
};
file_reader.readAsDataURL(file);
}
const handleSubbmitFile = (e) => {
e.preventDefault();
if(!files) return;
uploadImage(files);
}
const uploadImage = async (base64EncodedImage) => {
try {
const config = {
headers:{
'Content-Type' : 'application/json'
}
}
const body = JSON.stringify({files: base64EncodedImage});
await axios.post('/api/blogs/multer', body, config);
} catch (error) {
console.log(error);
}
}
return(
<form onSubmit={handleSubbmitFile} className="form-outline">
<input name="image" onChange={handleChange} type="file"
class="form-control-file" id="exampleFormControlFile1"
accept="image/*"/>
</form>
)
}
解决方案
我发现了问题,并通过在 handleSubbmitFile 中使用 formData 来修复它,并使用 append 将属性字段设置为 image。
const handleSubbmitFile = (e) => {
e.preventDefault(); //NOTE prevent from reload the page
let formData = new FormData();
for(var i = 0 ; i < files.length; i++){
formData.append('image',files[i])
}
if(!files) return;
uploadImage(formData);
}
另一个问题是在使用 axios 之前使用 Json.stringify()。在通过 axios 将其发送到后端之前,我没有使用 Json.stringify() 来转换 formData。结果,Multer 运行良好,没有问题
const uploadImage = async (formData) => {
try {
const config = {
headers:{
'Content-Type' : 'application/json'
}
}
await axios.post('/api/blogs/multer', formData, config);
} catch (error) {
console.log(error);
}
}
推荐阅读
- android - Fire Stick 4k - ADB 隐藏更新(禁用更新)权限错误
- reactjs - 如何使 Webpack 5 在我的 Docker 容器中可用?
- python - Python使用特定键将所有字典值设置为小写
- html - 如何对齐复选框长标签?
- javascript - 如何将其他选项中的相同值发布到服务器
- flutter - 如何隐藏 pdf 查看器插件颤动中存在的导航栏
- c# - ASP.NET Core IOptions - 是否可以从生产环境中的环境变量填充配置 POCO 敏感字段?
- typescript - Rollup.js 不会在包中包含节点模块 discord-rpc。有没有办法做到这一点?
- automation - 我想测试提交表单,但单击提交按钮会调用来自赛普拉斯不同域的 api
- asp.net-core - 通用存储库模式中的当前用户(ASP.NET 身份)信息