我正在尝试使用 React 前端和 Express 服务器将图像上传到 cloudinary。 问题是我无法正确地将请求图像发布到我的 express 服务器。
这就是我准备图像以便稍后发送的方法:
var data = new FormData();
console.log(event.target.files[0]) // this prints FileObject succesfully
data.append('image', event.target.files[0]);
console.log(data) // this prints {} but i guess its natural since its FormData ??
this.imageToUpload = data;
这就是我发布请求的方式:
axios.post('/api/courses/uploadImage',this.imageToUpload, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then( (response) => {
alert(JSON.stringify(response));
})
.catch(function (error) {
console.log(error);
});
现在在服务器端,req.body
为空。
router.post("/courses/uploadImage",(req,res,next)=>{
console.log(req.body) // empty
var image = req.body;
cloudinary.uploader.upload(image, function(error, result) { console.log(result) });
})
另外,我应该将什么真正放入(本例中为图像)uploader.upload
的第一个参数?
最佳答案
不是直接的答案,但如果您想要,Cloudinary 还提供了一种直接从前端上传图像的方法,这样可以节省您的一些工作。您可以read here further .
我使用过他们的小部件,它可以非常简单地集成到几乎任何应用程序中。
关于javascript - 将图像上传到 Cloudinary Express.js React Axios post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54469133/