上传图片到 Cloudinary Express.js React Axios post 请求

Uploading Image to Cloudinary Express.js React Axios post request

我正在尝试使用 React 前端和 Express 服务器将图像上传到 cloudinary。 问题是我无法正确地 post 向我的快递服务器请求图像。

这是我准备稍后发送的图片的方式:

          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;

这就是我 post 请求的方式:

 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.

我使用过他们的小部件,它很容易集成到几乎所有应用程序中。

我通过使用他们的 html5 codepen 示例直接将图像从客户端上传到 cloudinary 解决了我的问题。

你可以这样做。我已经在我的项目中尝试成功了。

function upload(){
  var data = new FormData();
  data.append('image', event.target.files[0]);
  data.append('username', 'Saurabh'); //if you have other fields

  axios.post('/api/courses/uploadImage', data,
   headers: {
    //your headers
   })
  .then( (response) => {
   alert(JSON.stringify(response));
  })
  .catch(function (error) {
   console.log(error);
  });
}

在您的快速路线中,您可以简单地获取这样的值

router.post('/api/courses/uploadImage', upload.single('image'), async(req,res, next) => {

 const result = await cloudinary.v2.uploader.upload(req.file.path);
 console.log(req.body.username); //Saurabh

 //your logic

});