【问题标题】:Uploading a base64 image from react-webcam to cloudinary via Node通过 Node 将 base64 图像从 react-webcam 上传到 cloudinary
【发布时间】:2020-05-02 22:13:35
【问题描述】:

我是新来的反应,任何帮助表示赞赏。 在通过 Node 将 jpg 上传到 cloudinary 时,我有以下代码可以使用。

onChange in 调用如下方法;

uploadProfilePic = e => {
  const files = Array.from(this.state.profilePic)
  const formData = new FormData()

  files.forEach((file, i) => {
    formData.append(i, file)
  })
    fetch(`http://localhost:3030/imageUpload`, {
      method: 'POST',
      body: formData
    })
    .then(res => res.json())
    .then(images => {
      this.setState({profilePic: images[0].url})
    })
  }

在我的 server.js 文件中;

  const values = Object.values(req.files)
    const promises = values.map(image => cloudinary.uploader.upload(image.path))

    Promise
      .all(promises)
      .then(results => res.json(results))
  })

以上成功将 jpg 上传到 cloudinary 并按预期将 url 设置为我的状态。

只是想知道如何调整上面的 2 个代码块,以便能够上传通过 react-webcam 捕获的 base64 图像*,该图像存储在我的状态 {this.state.passImage} 中以实现相同的结果(又名上传到 cloudinary 并检索 URL)?

到目前为止我已经尝试过

uploadPassImage= e => {

const formData = JSON.stringify(this.state.passImage)

    fetch(`http://localhost:3030/imageUploadPassImage`, {
      method: 'POST',
      body: formData
    })
    .then(res => res.json())
    .then(images => {
      this.setState({passImage: images[0].url})
    })
  }

带有服务器代码;

  app.post('/imageUploadPassImage', (req, res) => {
    const values = Object.values(req.files)
      const promises = values.map(image => cloudinary.uploader.upload(image.path))

      Promise
        .all(promises)
        .then(results => res.json(results))
    })

没有运气。

【问题讨论】:

    标签: javascript node.js reactjs express cloudinary


    【解决方案1】:

    我想通了。对于任何想知道或遇到相同问题的人,我会在这里发布。

    反应

    uploadPassImage= e => {
    const files = Array.of(this.state.passImage)
    
    
        const formData = new FormData()
    
        files.forEach((file, i) => {
          formData.append(i, file)
        })
          fetch(`http://localhost:3030/imageUploadPassImage`, {
            method: 'POST',
            body: formData
          })
          .then(res => res.json())
          .then(images => {
            this.setState({passImage: images[0].url}) 
    //sets the data in the state for uploading into SQL database later
          })
        }
    

    在服务器上;

    app.post('/imageUploadPassImage', (req, res) => {
       const values = Object.values(req.body)
          const promises = values.map(image => cloudinary.v2.uploader.upload(image,
      function(error, result) {console.log(result, error); }));
    
          Promise
            .all(promises)
            .then(results => res.json(results))
        })
    

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 2017-12-01
      • 2014-08-09
      • 2015-12-25
      • 2021-03-20
      • 2016-02-02
      • 2021-09-28
      • 2019-04-24
      • 2015-02-21
      相关资源
      最近更新 更多