简体   繁体   中英

How to retrieve image from nodejs backend to react

I have uploaded image by using multer library in express. in path Backend->Uploads/ and stored image path in mongodb.

I have project structure as

DirectoryName
  Backend
     Uploads
  Frontend

I can get the image path in frontend component , but How to get actual images from backend folder. Can I use file moving to store it in public in frontend , or retrieve stream from server. Will moving File from backend to frontend works actually in deployment.

I think you have done most of the work. Just set the image source or uri to the path and it will serve the image.

A simple example of implementation from one of my projects. Mayby not the best, but it works and, most important, you can get the idea. In this case I keep files on server.

Created a route in my API:

router.get('/download/:photo_id', async (req, res) => {
  try {
    const photo = await Photo.findOne({
      photoID: req.params.photo_id,
    });
    if (!photo) {
      return res.status(404).json({ msg: 'Photo not found' });
    }
    const filename = photo.photoFileName;
    const downloadPath = path.join(__dirname, '../../../imgs/', `${filename}`);
    res.download(downloadPath);
  } catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
      return res.status(404).json({ msg: 'Photo not found' });
    }
    res.status(500).send('Server error');
  }

});

And this route is called from front something like this:

    const handleDownload = async () => {
    const res = await fetch(`/api/photo/download/${photoID}`);
    const blob = await res.blob();
    download(
      blob,
      `${photoID}-${title}-${contributorName}.jpg`
    );
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM