我有一个MERN堆栈应用程序,我想提交一个包含文件输入和普通文本输入的表单,将提交的表单发送到redux操作,并且在该操作内部,我正在使用formData将图像转换为二进制格式并使用formData.append和axios .post将其发送到后端,在后端,我通过上载了通常的multer代码与upload.single('photo')。后端本身可以工作,我曾与邮递员一起测试过。 前端REDUX操作:
// update user info
export const updateUser = (userData, id) => dispatch => {
var form = new FormData()
console.log(userData.photo);
if (userData.photo) {
form.append('photo', userData.photo);
}
axios
.post("http://localhost:4000/api/users/update/" + id, userData)
.then(res => {
axios
.post('http://localhost:4000/api/users/upload_photo/' + id, form)
.then(res => {
const { user } = res.data;
console.log(user);
//save new user to localStorage
localStorage.setItem("user", JSON.stringify(user));
//dispatch to reducer
dispatch({
type: UPDATE_USER,
payload: user
})
})
})
}
BACKEND API
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/user');
},
filename: function (req, file, cb) {
cb(null, req.params.id + "_" + Date.now() + "_" + Math.floor(Math.random() * 10000) + file.originalname);
}
});
let upload = multer({ storage: storage })
//profile picture upload
router.route('/upload_photo/:id').post(upload.single('photo'), function (req, res) {
User.findById(req.params.id, function (err, user) {
if (err) {
res.status(404).send("user is not found");
}
else {
user.photo = {};
user.photo.path = req.file.path;
user.save().then(() => {
res.json({ message: 'picture uploaded!', user: user });
})
.catch(err => {
res.status(400).send("Upload not possible");
});
}
})
});