0

I want to use res.download() to download certain files from a server, however when I trigger the res.download it does not take the client to the correct url. The files to be downloaded are in a directory which has been set statically.

Here is my relevant backend code:

app.get("/downloadfile", function(req,res){
    var file = req.query.file;
    var currentpath = req.query.currentpath;
    console.log("SENDING FILE: " + file + " at: " + currentpath);
    //file = file.substring(20, file.length)
    console.log(file);
    console.log(currentpath + "/" + file);
    res.download(currentpath + "/" + file, file);
})

Here is the terminal output when I trigger this section of code:

SENDING FILE: Matthew Haywood CV.pdf at: /media/pi/ELEMENTS B//Matt Haywood/Uni Work
Matthew Haywood CV.pdf
/media/pi/ELEMENTS B//Matt Haywood/Uni Work/Matthew Haywood CV.pdf

This shows that the path supplied to the res.download function is correct and there is nothing wrong with the front end code otherwise an error would have been seen here.

This is what Safari returns when this route is triggered:

enter image description here

Why does res.download direct to /path_to_file/your_file.pdf/ instead of server/path_to_file/your_file.pdf?

When I go to the url manually the file downloads no problem but when using the res.download() it goes to the wrong url.

Matthew Haywood
  • 80
  • 3
  • 13

2 Answers2

2

You jest need to add a location header:

res.set({
    'Location': "url"
});
res.download(currentpath + "/" + file, file);
0

I managed to get it to work by adding on the client side:

window.location = "http://" + window.location.host + link;

in the AJAX call.

Matthew Haywood
  • 80
  • 3
  • 13