简体   繁体   English

Express res.download() 没有向客户端发送正确的 url

[英]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.我想使用 res.download() 从服务器下载某些文件,但是当我触发 res.download 时,它不会将客户端带到正确的 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:这是我触发这段代码时的终端output:

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.这表明提供给 res.download function 的路径是正确的,前端代码没有任何问题,否则会出现错误。

This is what Safari returns when this route is triggered:这是触发此路由时 Safari 返回的内容:

在此处输入图像描述

Why does res.download direct to /path_to_file/your_file.pdf/ instead of server/path_to_file/your_file.pdf?为什么 res.download 直接到 /path_to_file/your_file.pdf/ 而不是 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.当我手动从 go 到 url 时,文件下载没有问题,但是当使用 res.download() 时,它会转到错误的 url。

You jest need to add a location header:您开玩笑需要添加一个位置 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.在 AJAX 调用中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM