【问题标题】:Uploading Image to Cloudinary Express.js React Axios post request将图像上传到 Cloudinary Express.js React Axios 发布请求
【发布时间】:2019-06-25 10:03:06
【问题描述】:

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

这就是我准备图像以稍后发送的方式:

          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 的第一个参数?

【问题讨论】:

标签: javascript reactjs express axios cloudinary


【解决方案1】:

不是一个直接的答案,但如果您想要 Cloudinary 还提供了一种直接从您的前端上传图像的方法,这样可以为您节省一些工作。你可以read here further

我使用过他们的小部件,它可以非常简单地集成到几乎任何应用程序中。

【讨论】:

    【解决方案2】:

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

    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
    
    });
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2021-03-20
        • 1970-01-01
        • 2021-05-06
        • 2015-02-21
        • 2017-07-12
        • 2014-11-25
        • 2021-03-04
        • 2021-11-02
        • 2019-02-14
        相关资源
        最近更新 更多