使用blob以角度2下载xlsx文件

reu*_*eut 10 blob typescript angular

我想使用rest api从角度为2的客户端下载xlsx文件.

我得到一个字节数组作为我的GET请求的响应,我将它发送到订阅的下载功能:

let options = new RequestOptions({ search: params });
this.http.get(this.restUrl, options)
          .subscribe(this.download); 
Run Code Online (Sandbox Code Playgroud)

使用blob下载功能:

download(res: Response) {
let data = new Blob([res.arrayBuffer()], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
FileSaver.saveAs(data, this.fileName);};
Run Code Online (Sandbox Code Playgroud)

我的问题是我的文件一直都被破坏了.我尝试了很多这个版本,但没有任何作用.

**也尝试了这个解决方案,它不起作用(xlsx文件仍然被破坏) - Angular 2下载文件:损坏结果,不同的是我的数据是一个数组缓冲区而不是字符串或json,并在那里是PDF和xlsx之间的区别.

10倍!

Ver*_*tti 11

我遇到了与你相同的问题 - 通过添加responseType: ResponseContentType.Blob到我的获取选项修复它.检查以下代码:

public getReport(filters: ReportOptions) {
    return this.http.get(this.url, {
            headers: this.headers,
            params: filters,
            responseType: ResponseContentType.Blob
        })
        .toPromise()
        .then(response => this.saveAsBlob(response))
        .catch(error => this.handleError(error));
}
Run Code Online (Sandbox Code Playgroud)

saveAsBlob()只是FileSaver.SaveAs()的包装器:

private saveAsBlob(data: any) {
    const blob = new Blob([data._body],
        { type: 'application/vnd.ms-excel' });
    const file = new File([blob], 'report.xlsx',
        { type: 'application/vnd.ms-excel' });

    FileSaver.saveAs(file);
}
Run Code Online (Sandbox Code Playgroud)

  • 作品!我的问题中缺少的关键部分是设置 `responseType: 'blob'` (使用 axios),甚至不需要 `const file = ...`。刚刚制作了一个“blob”,然后做了“FileSaver.saveAs(blob, 'report.xlsx')” (3认同)
  • 嗨,这也适用于我,但我已经更改了 ```responseType: 'blob'```,这适用于我的两个文件 ```.csv``` 和 ```.xlsx``` 类型的文件。请找到我的代码....```return this.http.get(url, { headers: headers, responseType: 'blob', observe: 'response' });``` (2认同)

reu*_*eut 6

什么都行不通.我更改了我的服务器以返回相同的字节数组,并添加:

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment; filename=deployment-definitions.xlsx");
Run Code Online (Sandbox Code Playgroud)

在我的客户端,我删除了下载功能,而不是我做的GET部分:

window.open(this.restUrl, "_blank");
Run Code Online (Sandbox Code Playgroud)

这是我发现可以保存未损坏的xlsx文件的唯一方法.

如果你有关于如何用blob做的答案,请告诉我:)