【问题标题】:Angular 6: downloading file issueAngular 6:下载文件问题
【发布时间】:2019-04-10 22:36:02
【问题描述】:

我遇到了一个问题,但我找不到任何解决方案。因此,如果这个问题以某种方式与其他人重复,我提前道歉。

问题是我正在向后端发送GET 请求并得到响应。响应正文中有Blob。我试图下载它,但在我得到一个文件名来命名我的下载文件之前。并且在本地一切正常。但在外部版本文件不会下载。单击按钮后我有响应,我看到我进入了FileUtil 中的保存功能。但是下载没有开始。有人能知道问题是什么吗?

这是 Chrome 检查工具中网络选项卡中的响应(您可以看到所有标头都在接收)

download.service.ts

downloadFile(id: string) {
    return this.apiService.getFile(id).pipe(
        map(response => {
            const data = response.body;
            const blob = new Blob([data], { type: 'application/zip' });
            FileUtil.save(blob, this.getFileName(response.headers));
        })
    )
}

private getFileName(headers: HttpHeaders) {
    const contentDisposition = headers.get('Content-Disposition') || '';
    const matches = /filename=([^;]+)/ig.exec(contentDisposition);
    const fileName = (matches[1] || 'file.zip').trim();
    return fileName;
}

api.service.ts

getFile(id: string): Observable<HttpResponse<Blob>> {
    return this.httpClient.get<Blob>(requestUrl, {responseType: 'blob' as 'json', observe: 'response'});
}

FileUtil.ts

static save(data: Blob, name: string) {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(data);
    a.href = url;
    const filename = name;
    a.download = filename;
    a.click();
    setTimeout(() => {
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    }, 0);
}

【问题讨论】:

标签: angular typescript


【解决方案1】:

问题的原因是缺少('Access-Control-Expose-Headers', 'Content-Disposition') 并且浏览器不知道我的响应是他应该下载的附件。所以检查你的响应的标题两次。

【讨论】:

    【解决方案2】:

    你可以这样试试

    FileUtil.ts

     save(data: Blob, name: string) {
       const a = document.createElement('a');
       document.body.appendChild(a);
       const blob = new Blob([data], { type: 'octet/stream' });
       const url = window.URL.createObjectURL(data);
       a.href = url;
       a.download = "filename.csv"; // you need to write the extension of file here
       a.click();
       window.URL.revokeObjectURL(url);
      })
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 2019-01-08
      • 2019-06-05
      • 2019-03-29
      • 1970-01-01
      • 2019-01-18
      • 2019-08-20
      • 1970-01-01
      相关资源
      最近更新 更多