透過 FileSaver 處理檔案下載方案

在 Angular 中,處理檔案下載不是一件容易的事情,主要方法有以下兩種:

1. 透過 anchor 直接將檔案的下載連結放在網頁上:

<a href="/vpn/downloadFile?filename={{item.patientFile}}" class="btn btn-info btn-sm" type="button"
   ng-disabled="!item.patientFile" icon="fa-file-excel-o" target="_self">
    下載 Excel
</a>

其中 /vpn/download 就是用來下載檔案的方式

2. 直接在 angular client code 中處理

最快的方案(而且不需要花費時間)就是透過 HTML 5 FileSaver 套件,引用方式如下:

  • 下載 npm package,這裡同時下載 typescript 定義檔,提供 Intellisense:

npm install file-saver –save

npm install @types/file-saver –save

透過 –save 會直接 update package.json file

  • 透過 http get 下載檔案:
download() {
    this.http.get("/dailyreport/downloadExcel/" + id, { responseType: 'blob' })
        .subscribe(
            data => this.processFile(data),
            error => super.showMessage(AlertType.Danger, error)
        );
}
 
private processFile(data: any) {
    var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
    FileSaver.saveAs(blob, "file.xlsx");
}

注意這裡使用 blob 型態。

  • 在 Server side 將檔案轉成 filestream:
[HttpGet]
public IActionResult DownloadExcel(string filePath)
{
    var fileContents = System.IO.File.ReadAllBytes(filePath);
    return new FileContentResult(fileContents, "application/vnd.ms-excel");
}

 

 

有問題嗎?歡迎一起討論喔!