0

I've managed to upload images into the folder "backend/resources/static/assets/uploads/". How do I retrieve and display the images in the frontend? I've tried to download the image using this bit of code:

  const download = (filename) => {
    return axios.get(baseUrl+`/files/${filename}`)
  }

and this in the backend:

uploadRouter.get('/files/:name', async (req, res) => {
  const fileName = req.params.name

  const directoryPath = __basedir + "/resources/static/assets/uploads/"

  res.download(directoryPath + fileName, fileName, (err) => {
    if (err) {
      res.status(500).send({
        message: "Could not download the file. " + err,
      })
    }
    res.sendFile(`${directoryPath + fileName}`)
  })
  })

but I have no idea how to display the downloaded picture in the React app. I'm a beginner in using multer so any help is appreciated

edit:

I'm now trying to do:

  const showPicture = async (user) => {
    const imageName = user.avatar
    uploadService.download(imageName)
    .then(res => {
      console.log(res.data)
    })
    .then(imageBlob => {
      const imageObjectURL = URL.createObjectURL(imageBlob)
      console.log(imageObjectURL)
      setPicture(imageObjectURL)
    })

but I'm getting "Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed."

  • You need the convert the response into a blob and then convert into a url.Checkout this post -https://stackoverflow.com/a/50248437/13824894 – RobLjm Sep 25 '22 at 07:51
  • I'm getting "Uncaught (in promise) TypeError: res.data.blob is not a function" and "Uncaught (in promise) TypeError: res.blob is not a function" – anoleguaani Sep 25 '22 at 08:21
  • I fixed that by adding "{responseType: 'blob'})" to axios request, but now I'm getting "Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed." – anoleguaani Sep 25 '22 at 08:31

0 Answers0