Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading