Search code examples
reactjsmongooseaxiosmulter

how to get images from mongo with axios and display them with react


The server route:

router.get('/images', async (req, res) => {
const image = await Image.findOne({})

res.json(image)
})

Axios:

const image = await Axios.get("http://localhost:5000/images/images")
setAvailableFile(image.data.img.data)

if console.log availableFile i get:

img:
   contentType: "image/jpeg"
   data: {type: "Buffer", data: Array(11615)}
   __proto__: Object
   name: "download.jpg"
   __v: 0
   _id: "5feb25dff4b7b43344a92952"

react:

  <div>
      {availableFile && availableFile.data}
  </div>

now the thing is, when i try to display the image i get something like:

255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,219,0,132,0,9,6,7,16,16,15,21,16,15,15,16,21,16....

any ideas? thanks in advance!


Solution

  • Ok so i figured it out, i'll share the solution. to make this work i needed to do 2 things:

    1. the first one is what @Viet said.

    2. and then i need to add {image.img.data.toString('base64')} to the get request:

      router.get('/images', async (req, res) => {
            const image = await Image.findOne({})
      
            res.json(image.img.data.toString('base64'))
      })