Dworo
Dworo

Reputation: 163

Uploading a base64 image from react-webcam to cloudinary via Node

I'm new to react and any help is appreciated. I have the following code that works when it comes to uploading a jpg with to cloudinary via Node.

onChange in calls the following method;

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

and in my server.js file;

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

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

above successfully uploads the jpg to cloudinary and sets the url to my state as intended.

Just wondering how to tweak the 2 code blocks above to be able to upload a base64 image* that was captured via react-webcam which is stored in my state {this.state.passImage} to achieve the same result(aka upload to cloudinary and retrieve the URL)?

so far I've tried

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

with the server code;

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

with no luck.

Upvotes: 1

Views: 1612

Answers (1)

Dworo
Dworo

Reputation: 163

I figured it out. For anyone wondering or encountering the same issue, I'll post it here.

on react

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

on the server;

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

Upvotes: 1

Related Questions