Angular 无法使用 res.download 从 Express 获取文件下载

2024-03-08

在我的应用程序中,我在后端创建一个文件,然后我希望通过浏览器下载将其传递给用户。我已经尝试过无数次

这是 Express 后端:

app.get('/download', (req, res) => {
  res.download('filename.txt', function (err) {
    console.log(err);
  });
})

控制台调用没有返回,因此可能没有错误。这是我在前端所做的事情,遵循建议here https://stackoverflow.com/questions/20176982/res-download-not-working-in-my-case和这里:

window.open('localhost:3000/download');

结果是我弹出一个空白窗口,但没有下载。我也尝试过this https://stackoverflow.com/questions/35164277/download-file-on-ajax-success-node-js:

const filePath = 'localhost:3000/download/';
const link = document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();

但在这种情况下,什么也没有发生。

我究竟做错了什么?我什至不知道如何进一步调试。

Update 1

谢谢@jal_a,我已经取得了进步。我现在意识到,如果我手动创建一个窗口并输入网址(按照建议),下载就可以进行。但是,当使用应用程序从应用程序启动窗口时window.open(url)如果 url 相同,则会打开窗口,但不会启动下载。如果我随后转到创建的窗口,单击 url 并按回车键...瞧!有用!如何从应用程序启动窗口启动下载?

Update 2

谢谢@IceMetalPunk,我尝试了一下,在控制台中收到以下错误 - 我尝试下载的文件是 gpx 格式的 gps 数据 - 我可以在响应中看到它,但它似乎期待 JSON? ?我需要进行任何预处理才能发送文件吗?:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", 
url: "http://localhost:3000/download/", ok: false, …}
error:
error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse 

...

text: "<?xml version="1.0" encoding="UTF-8"?>
↵<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/0">
↵   <rte>
↵      <name>undefined</name>
↵      <rtept lat="50.70373" lon="-3.07241" />
↵      <rtept lat="50.70348" lon="-3.07237" />
↵   </rte>
↵</gpx>"
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: 
ƒ}
message: "Http failure during parsing for http://localhost:3000/download/"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:3000/download/"
__proto__: HttpResponseBase

问题是我的下载链接不包含http://url 的元素,如这个答案 https://stackoverflow.com/questions/54053901/cannot-get-browser-to-initiate-download-from-express描述。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 无法使用 res.download 从 Express 获取文件下载 的相关文章

随机推荐