-1

I send an image file to my node server via my react app -

I want to host these images on google cloud or similar so they have an accessible URL.

I have tried using cloudinary and google cloud but to no avail thus far!

My react-side code (shortened):

imageFile = this.state.files[0])

        const formData = new FormData()
        formData.append('file', imageFile);
        sendImage(formData)

    sendImage(image) {
      axios.post("https://137a6167.ngrok.io/image-upload", image, { 
      })
       .then(res => { // then print response status
       console.log(res.statusText)
      })
     }

The file is successfully sent to my server and consoled:

  app.post('/image-upload', (req, res) => {
  console.log('consoling the req.body!!!!' + JSON.stringify(req.body))
  })

THE CONSOLE: consoling the req.body!!!!{"1":"[object File]"}

I did try use this following cloudinary method, yet it threw errors:

  cloudinary.config({ 
  cloud_name: process.env.CLOUD_NAME, 
  api_key: process.env.API_KEY, 
  api_secret: process.env.API_SECRET
  })

app.use(formData.parse())

app.post('/image-upload', (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))
})

this gave me the error that an unhandled error in the promise wasnt handled and i got a bit lost with where to go beyond that!

I looked at google cloud storage too but couldn't get it working! Any advice?

What I really want to do is return back to my react app the URL of the hosted image - so it can be stored in DB for the user!

If you can help at all that would be greatly appreciated, thank you.

Sparlarva
  • 790
  • 1
  • 8
  • 30

1 Answers1

0

There are couple of things you need to fix on the front end before you try to upload to any cloud.

First you need to set 'Content-Type': 'multipart/form-data' header in axios to send the file data properly.

Check this thread for more details: How do I set multipart in axios with react?

Then on the express side you need multer or some other similar library to receive the data. You can't access it from req.body. multer adds req.files for example.

https://github.com/expressjs/multer

Try there steps and then post the exact error message you are receiving from google cloud.

King Julien
  • 10,981
  • 24
  • 94
  • 132