What's the best way to trigger a file download from Node.js backend using a frontend link?

I’m working on a project where users can upload and delete files. I want them to be able to download these files using a simple link on the frontend. Here’s what I’ve tried so far:

<a href='/get-file?name=example.pdf'>Download File</a>

On the server side, I have this:

app.get('/get-file', (req, res) => {
  const filePath = `./uploads/${req.query.name}`;
  res.sendFile(filePath);
});

But it’s not working as expected. The file opens in the browser instead of downloading. How can I make sure the file downloads when the link is clicked? Do I need to use JavaScript or can I do this with just HTML and Express? Any help would be great!

To trigger a file download from your Node.js backend, you can modify your server-side code to set the appropriate headers. Here’s an improved version of your Express route:

app.get('/get-file', (req, res) => {
  const filePath = `./uploads/${req.query.name}`;
  const fileName = req.query.name;

  res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);
  res.setHeader('Content-Type', 'application/octet-stream');

  res.sendFile(filePath, (err) => {
    if (err) {
      console.error('Error sending file:', err);
      res.status(500).send('Error downloading file');
    }
  });
});

This approach sets the Content-Disposition header to ‘attachment’, which prompts the browser to download the file instead of displaying it. The Content-Type header ensures the file is treated as a binary stream. Remember to handle potential errors for a more robust solution.

yo SwimmingFish! u could try using the ‘download’ attribute on ur tag. it’s pretty simple:

Download File

this tells the browser to download instead of open. no extra server-side stuff needed. might save u some headaches! good luck with ur project!

hey there! have u tried setting the Content-Disposition header? it can force downloads instead of browser display. like this:

res.setHeader(‘Content-Disposition’, ‘attachment; filename=example.pdf’);

maybe that’ll help? let me kno if u need more info! what kinda files r ur users uploading?