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

时间:2021-12-19 09:56:46

I want to download xlsx file from the client on angular 2 using rest api.

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

I'm getting a byte array as a response from my GET request and I'm sending it to download function with subscribe:

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

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

download function using blob:

使用blob下载功能:

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

my problem is that my file is corrupted all the time. I tried a lot of versions of this but nothing works.

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

** also tried it with this solution and it doesn't works (the xlsx file is still corrupted) - Angular 2 downloading a file: corrupt result , the difference is that my data is an array Buffer and not string or json, and there is a difference between PDF and xlsx.

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

10x!

10倍!

5 个解决方案

#1


6  

I was having the same problem as yours - fixed it by adding responseType: ResponseContentType.Blob to my Get options. Check the code below:

我遇到了和你一样的问题 - 通过在我的Get选项中添加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));
}

The saveAsBlob() is just a wrapper for the FileSaver.SaveAs():

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);
}

#2


3  

After nothing works. I changed my server to return the same byte array with the addition of:

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

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

At my client I deleted the download function and instead of the GET part i did:

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

window.open(this.restUrl, "_blank");

This is the only way I found it possible to save an xlsx file that is not corrupted.

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

If you have a answer about how to do it with blob please tell me :)

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

#3


1  

you can use the below code :

你可以使用下面的代码:

var file = new Blob([data], { 
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
});
saveAs(file,"nameFile"+".xlsx");
deferred.resolve(data);

#4


0  

The following solution worked for me in Google Chrome Version 58.0.3029.110 (64-bit).

以下解决方案适用于Google Chrome版本58.0.3029.110(64位)。

It's an article explaining how to download a pdf using a Blob: https://brmorris.blogspot.ie/2017/02/download-pdf-in-angular-2.html

这篇文章解释了如何使用Blob下载pdf:https://brmorris.blogspot.ie/2017/02/download-pdf-in-angular-2.html

It's the same principle for a xlsx file. Just follow the steps from the article and change two things:

这与xlsx文件的原理相同。只需按照文章中的步骤操作即可更改两件事:

  • Header, instead of {'Accept': 'application/pdf'}, use {'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'};
  • 标题,而不是{'Accept':'application / pdf'},使用{'Accept':'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'};
  • Blob, use the same type for the creation of your Blob, new Blob([fileBlob], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}).
  • Blob,使用相同的类型创建Blob,新Blob([fileBlob],{type:'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'})。

The article is using File Saver but I didn't. I left a comment, in the article, with a basic explanation of what I used instead of File Saver.

这篇文章正在使用File Saver,但我没有。我在文章中留下了一条评论,其中基本解释了我使用的是File Saver。

#5


0  

Here is the solution that supports IE and chrome/safari browsers. Here 'response' object is response received from service. I have this working for archive. You can change the type as per the response received from service.

这是支持IE和chrome / safari浏览器的解决方案。这里'响应'对象是从服务收到的响应。我有这个工作存档。您可以根据从服务收到的响应更改类型。

    let blob = new Blob([response], {type: 'application/zip'});
    let fileUrl = window.URL.createObjectURL(blob);
    if (window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileUrl.split(':')[1] + '.zip');
    } else {
        this.reportDownloadName = fileUrl;
        window.open(fileUrl);
    }

#1


6  

I was having the same problem as yours - fixed it by adding responseType: ResponseContentType.Blob to my Get options. Check the code below:

我遇到了和你一样的问题 - 通过在我的Get选项中添加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));
}

The saveAsBlob() is just a wrapper for the FileSaver.SaveAs():

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);
}

#2


3  

After nothing works. I changed my server to return the same byte array with the addition of:

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

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

At my client I deleted the download function and instead of the GET part i did:

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

window.open(this.restUrl, "_blank");

This is the only way I found it possible to save an xlsx file that is not corrupted.

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

If you have a answer about how to do it with blob please tell me :)

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

#3


1  

you can use the below code :

你可以使用下面的代码:

var file = new Blob([data], { 
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
});
saveAs(file,"nameFile"+".xlsx");
deferred.resolve(data);

#4


0  

The following solution worked for me in Google Chrome Version 58.0.3029.110 (64-bit).

以下解决方案适用于Google Chrome版本58.0.3029.110(64位)。

It's an article explaining how to download a pdf using a Blob: https://brmorris.blogspot.ie/2017/02/download-pdf-in-angular-2.html

这篇文章解释了如何使用Blob下载pdf:https://brmorris.blogspot.ie/2017/02/download-pdf-in-angular-2.html

It's the same principle for a xlsx file. Just follow the steps from the article and change two things:

这与xlsx文件的原理相同。只需按照文章中的步骤操作即可更改两件事:

  • Header, instead of {'Accept': 'application/pdf'}, use {'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'};
  • 标题,而不是{'Accept':'application / pdf'},使用{'Accept':'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'};
  • Blob, use the same type for the creation of your Blob, new Blob([fileBlob], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}).
  • Blob,使用相同的类型创建Blob,新Blob([fileBlob],{type:'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'})。

The article is using File Saver but I didn't. I left a comment, in the article, with a basic explanation of what I used instead of File Saver.

这篇文章正在使用File Saver,但我没有。我在文章中留下了一条评论,其中基本解释了我使用的是File Saver。

#5


0  

Here is the solution that supports IE and chrome/safari browsers. Here 'response' object is response received from service. I have this working for archive. You can change the type as per the response received from service.

这是支持IE和chrome / safari浏览器的解决方案。这里'响应'对象是从服务收到的响应。我有这个工作存档。您可以根据从服务收到的响应更改类型。

    let blob = new Blob([response], {type: 'application/zip'});
    let fileUrl = window.URL.createObjectURL(blob);
    if (window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileUrl.split(':')[1] + '.zip');
    } else {
        this.reportDownloadName = fileUrl;
        window.open(fileUrl);
    }