下载文件不起作用

Nof*_*fel 14 javascript angular

我是Javascript的新手,我想在承诺的结果后下载来自动态网址的文件,它是生成的pdf,我试图通过以下调用下载,但无法使其工作,因为下载没有开始

<button (click)='downloadMyFile()'>Download</button>

downloadMyFile(){
  //url 
  .then((result)=>{
   //result is contains a url www.abc.com/file234
    window.location.href = result
})
  .catch((error)=>{
   //myerror
})
}
Run Code Online (Sandbox Code Playgroud)

这是插件

Mar*_*mek 6

您可以像这样强制下载文件:

const link = document.createElement('a');
link.href = result;
link.download = 'download';
link.target = '_blank';
link.click();
Run Code Online (Sandbox Code Playgroud)

只需创建锚标记,设置其hrefdownload属性并触发click事件。

另请注意,这实际上并不是关于以扩展名结尾的 URL - 它更多的是关于您随文件响应(即Content-TypeContent-Disposition)发送的标头。


seb*_*ebu 1

<button (click)='downloadMyFile()'>Download</button>

downloadMyFile(){
  .then((result)=>{
       var a= document.createElement('a');
       a.href = result;
       a.download = 'download name';
       a.click();
   }).catch((error)=>{})
}
Run Code Online (Sandbox Code Playgroud)