我正在尝试使用带有反应库的axios发送带有另一个发布参数的文件“图像”,这是我的原始代码,可以很好地将一个图像或文件发送到服务器..使用multer库保存图像:
submitFormImagen(e){
e.preventDefault();
const token = localStorage.getItem('auth-token');
const formData = new FormData();
formData.append('myImage',this.state.file);
const config = {
headers: {
'content-type': 'multipart/form-data',
'auth-token': token
}
};
axios.post("http://localhost:5000/api/user/upload",formData,config)
.then((response) => {
alert("The file is successfully uploaded");
console.log(response)
this.setState({imagen: response.data.imagen})
}).catch((error) => {
});
}
在这种情况下:formData是multer库可以保存图像所必需的;这是我来自服务器的代码:
router.post('/upload', verificarToken, async function(req,res){
//imagen nombre: req.file.filename
console.log(req.body)
const url = req.protocol + '://' + req.get('host')
const _id = req.user._id
upload (req, res, async function(err) {
if(err) {
return res.end("Ocurrio un error al subir el archivo.");
}
const rutaimagen = url + "/uploads/" +req.file.filename
//Actualizar Imagen del usuario:
await User.findByIdAndUpdate(_id, {
imagen: rutaimagen
});
//res.end("Archivo subido correctamente!");
res.json({imagen: rutaimagen})
});
});
基本上就是现在,我正在尝试捕获请求正文以尝试更新用户图像及其名称和电子邮件。 此更新不起作用:
submitFormImagen(e){
e.preventDefault();
const token = localStorage.getItem('auth-token');
const formData = new FormData();
formData.append('myImage',this.state.file);
var post = {
myImage: this.state.file,
name: this.state.name,
email: this.state.email
}
const config = {
headers: {
'content-type': 'multipart/form-data',
'auth-token': token
}
};
axios.post("http://localhost:5000/api/user/upload",post,config)
.then((response) => {
alert("The file is successfully uploaded");
console.log(response)
this.setState({imagen: response.data.imagen})
}).catch((error) => {
});
}
我也尝试过:
formData.append('myImage',this.state.file);
var post = {
name: this.state.name,
email: this.state.email
}
formData.append('anotherdata',post);
const config = {
headers: {
'content-type': 'multipart/form-data',
'auth-token': token
}
};
axios.post("http://localhost:5000/api/user/upload",formData,config)
...
现在我正在尝试从位于上载路线内的服务器上载函数中的“ anotherdata”值。但是我得到了:
[Object: null prototype] { anotherdata: '[object Object]' }
这是服务器的代码:
router.post('/upload', verificarToken, async function(req,res){
//imagen nombre: req.file.filename
const url = req.protocol + '://' + req.get('host')
const _id = req.user._id
upload (req, res, async function(err) {
console.log(req.body) //<*********
if(err) {
return res.end("Ocurrio un error al subir el archivo.");
}