How to download files in React from Node server?

My backend:
files-routes.js:

router.get('/download/:fid', filesControllers.downloadFile);

filesControllers.js:

const downloadFile = async (req, res, next) => {
  const fileId = req.params.fid;
  let filePost;
  try {
    filePost = await File.findById(fileId);
  } catch (err) {
    return next(new HttpError("Error", 500));
  }
  console.log(filePost.file);
  res.download(filePost.file);
}

If I paste in the browser: ‘http://localhost:5000/api/files/download/fileId’, the file can be downloaded.

My frontend:

<Link to={`http://localhost:5000/api/files/download/${props.id}`} target="_blank" download>
  Download File
</Link>

When I click on the link, the file fails to download. Is there anything I should do? I have tried with fetch api try/catch block but still couldn’t get it to work.

>Solution :

Go for simple anchor tags.

React-router’s Link tags are good if that page lies on one of your routes. Otherwise, just use a simple anchor tags

<a href={article.url} target="_blank">
  <img src={article.urlToImage} alt="thumb"/>
</a>

Leave a Reply