簡體   English   中英

用帶blob的角度2下載xlsx文件

[英]downloading xlsx file in angular 2 with blob

我想使用rest api從角度為2的客戶端下載xlsx文件。

我得到一個字節數組作為我的GET請求的響應,我將它發送到訂閱的下載功能:

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

使用blob下載功能:

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

我的問題是我的文件一直都被破壞了。 我嘗試了很多這個版本,但沒有任何作用。

**也嘗試了這個解決方案,它不起作用(xlsx文件仍然被破壞) - Angular 2下載文件:損壞結果 ,不同的是我的數據是一個數組緩沖區而不是字符串或json,那里是PDF和xlsx之間的區別。

10倍!

我遇到了和你一樣的問題 - 通過在我的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));
}

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

什么都行不通。 我更改了我的服務器以返回相同的字節數組,並添加:

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

在我的客戶端,我刪除了下載功能,而不是我做的GET部分:

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

這是我發現可以保存未損壞的xlsx文件的唯一方法。

如果你有關於如何用blob做的答案,請告訴我:)

你可以使用以下代碼:

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

以下解決方案適用於Google Chrome版本58.0.3029.110(64位)。

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

這與xlsx文件的原理相同。 只需按照文章中的步驟操作即可更改兩件事:

  • 標題,而不是{'Accept':'application / pdf'},使用{'Accept':'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'};
  • Blob,使用相同的類型創建Blob,新Blob([fileBlob],{type:'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'})。

這篇文章正在使用File Saver,但我沒有。 我在文章中留下了一條評論,其中基本解釋了我使用的是File Saver。

這是支持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);
    }

對我來說問題是,我的responseType是“text”。 相反,我需要使用“blob”; 它適用於Angular 7.2.15。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM