简体   繁体   中英

Express res.download() does not send the correct url to client

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:

在此处输入图像描述

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.

You jest need to add a location header:

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

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

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

in the AJAX call.

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