在Angular 5中通过Blob下载时设置文件名

时间:2018-08-22 05:06:01

标签: angular angular5 blob

下面是我的Typescript代码,可以从API下载文件

DownloadLM() {
var ID= sessionStorage.getItem("UserID");
    return this.http.get(this.baseurl + 'api/DownloadFiles/DownloadLM/' + ID,
      {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: 'arraybuffer'
      }
    )
      .subscribe(respData => {
        this.downLoad(respData, this.type);
      }, error => {
      });
  }

  downLoad(data: any, type: string) {
    var blob = new Blob([data], { type: type.toString() });
    var url = window.URL.createObjectURL(blob);
    var pwa = window.open(url);
    if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
      alert('Please disable your Pop-up blocker and try again.');
    }
  }

下载Excel File很好,但是它给我不需要的文件一个随机名称,我想在下载时设置自己选择的文件名,

在哪里可以在此处设置文件名? Blob的任何属性?

3 个答案:

答案 0 :(得分:5)

您可以将download属性设置为所需的文件名,将href设置为对象url,然后只需单击即可。

var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();

答案 1 :(得分:5)

如果要获取上传文件的确切文件名,请从支持的API流中设置文件名的自定义标头。

您可以这样使用它:我的Excel API响应标头:

content-disposition: inline;filename="salesReport.xls" 
content-type: application/octet-stream 
date: Wed, 22 Aug 2018 06:47:28 GMT 
expires: 0 
file-name: salesReport.xls 
pragma: no-cache 
transfer-encoding: chunked 
x-application-context: application:8080 
x-content-type-options: nosniff 
x-xss-protection: 1; mode=block

Service.ts

excel(data: any) {
  return this.httpClient.post(this.config.domain + 
  `/api/registration/excel/download`,data, {observe: 'response', responseType: 'blob'})
  .map((res) => {
      let data = {
                     image: new Blob([res.body], {type: res.headers.get('Content-Type')}),
                     filename: res.headers.get('File-Name')
                  }
    return data ;
  }).catch((err) => {
    return Observable.throw(err);
  });
}

Component.ts

excelDownload (data) {
   this.registration.excel(data).subscribe(
    (res) => {
     const element = document.createElement('a');
      element.href = URL.createObjectURL(res.image);
      element.download = res.filename;
      document.body.appendChild(element);
      element.click();
     this.toastr.success("Excel generated  successfully");
    },
  (error) =>{
     this.toastr.error('Data Not Found');
  });
}

答案 2 :(得分:0)

由于有人要求提供带有承诺的版本,因此您可以使用await和async:

第1部分:从服务器获取Blob:

  generateSapExcel(data: GenerateSapExport): Promise<HttpResponse<Blob>> {
    return this.http.post(`${this.pathprefix}/GenerateSapExcel`, data, { responseType: 'blob', observe: 'response' })
      .toPromise()
      .catch((error) => this.handleError(error));
  }

第2部分:提取HttpResponse并将其交付给用户:

public downloadFile(data: HttpResponse<Blob>) {
    const contentDisposition = data.headers.get('content-disposition');
    const filename = this.getFilenameFromContentDisposition(contentDisposition);
    const blob = data.body;
    const url = window.URL.createObjectURL(blob);
    const anchor = document.createElement("a");
    anchor.download = filename;
    anchor.href = url;
    anchor.click();
  }

  private getFilenameFromContentDisposition(contentDisposition: string): string {
    const regex = /filename=(?<filename>[^,;]+);/g;
    const match = regex.exec(contentDisposition);
    const filename = match.groups.filename;
    return filename;
  }

第3部分:结合两者:

      const blobresponse = await this.dataService.generateSapExcel(dataToSend);
      this.downloadService.downloadFile(blobresponse);

第4部分:服务器:

        [HttpPost]
        [Route(nameof(GenerateSapExcel))]
        public async Task<FileStreamResult> GenerateSapExcel(GenerateSapExportDto dto)
        {
            Stream stream = await _sapKurepoService.GenerateSapExcel(dto);
            FileStreamResult result = File(stream, FileHelper.ContentypeExcel, "excel.xlsx");
            return result;
        }