reactjs - 反应:req.files 返回空白数组
问题描述
我有 Node.js 应用程序,由 express 提供服务,我的前端是用 React.js 制作的。我正在创建一个需要上传多个图像的组件。问题出在客户端发送数据后 req.files 返回一个空白数组。我还使用邮递员检查后端,它工作正常。唯一的问题是前端。
Client-side
const UserPost = () => {
const [postImageCollection, setPostImageCollection] = useState([]);
const handleImageCollection = async (e) => {
e.preventDefault();
const fdPayload = new FormData();
for (let i = 0; i < postImageCollection.length; i++) {
fdPayload.append('postImageCollection', postImageCollection[i]);
}
try {
await axios({
method: 'POST',
url: 'http://localhost:5000/user/posts',
data: fdPayload,
headers: {
'content-type': 'multipart/form-data',
},
}).then((res) => {
console.log(res);
});
} catch (error) {
console.log(error.response);
}
};
const handleChangeImageCollection = (e) => {
const newArray = [...postImageCollection];
for (let i = 0; i < e.target.files.length; i++) {
newArray.push({ src: URL.createObjectURL(e.target.files[i]) });
}
setPostImageCollection(newArray);
if (newArray.length > 5) {
setCurrentImageHide('+' + (newArray.length - imagePerPost));
}
};
return (
<Container
component='div'
className={classes.userPostContainer}
style={{ padding: '0', margin: '0' }}
>
<Card className={classes.userPostCard} style={{ boxShadow: 'none' }}>
<CardContent style={{ padding: '0 0 1.5em 0' }}>
<form noValidate onSubmit={handleImageCollection}>
<Grid container>
<Grid
xs={12}
className={classes.postPhotoContainer}
style={{ padding: '0' }}
>
<ImageList
postImageCollection={currentImage}
currentImageHide={currentImageHide}
/>
<input
accept='image/*'
id='postImageCollection-file-button'
type='file'
name='postImageCollection'
onChange={handleChangeImageCollection}
multiple
style={{ display: 'none' }}
/>
<label htmlFor='postImageCollection-file-button'>
<ImageIcon />
Photo
</label>
</Grid>
<Button
type='submit'
variant='contained'
className={classes.button}
style={{ width: '60%', marginBottom: '2.5rem' }}
>
Upload
</Button>
</Grid>
</form>
</CardContent>
</Card>
</Container>
);
};
Backend
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images/post');
},
filename: function (req, file, cb) {
cb(
null,
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
);
},
});
const upload = multer({
storage,
limits: {
fileSize: '2mb',
},
fileFilter: (req, file, cb) => {
if (
file.mimetype == 'image/png' ||
file.mimetype == 'image/jpg' ||
file.mimetype == 'image/jpeg'
) {
cb(null, true);
} else {
cb(null, false);
return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
}
},
});
router.post(
'/user/posts',
upload.array('postImageCollection', 12),
function (req, res, next) {
console.log(req);
}
);
注意: postImageCollection 是字段名,也是猫鼬模式中的字段名
谢谢!
解决方案
推荐阅读
- jquery - 动画仅在 DOM 的鼠标悬停状态下出现故障
- amazon-web-services - 在 Jenkins 上建立工作后,工作被杀死
- python - 迭代数据框的一列
- ios - macOS 上的 SwiftUI,如何使整行可点击?
- r - 读回拟合生存模型的输出
- java - 关于向 1:1 聊天发送消息的 Microsoft 图形 API 权限
- node.js - 如何按类型获取请求?
- github - 使用 Git LFS 将视频添加到自述文件
- javascript - 在同一个流屏幕上验证多个所需的 LWC,而不会丢失值
- python - Asyncio .create_task() 未运行传入的函数