首页 > 解决方案 > 如何在 Angular cli 中下载文件?

问题描述

下载文件时遇到问题,当我从后端收到响应时,如何下载文件?

错误是当我想获取文件名时

这是我的 .ts :

async download(path: any) {
    const { status, headers, body } = await this.studentService.download(path);
     const filenames = this.Filename(headers);
    const blob = new Blob([body],{type:'application/octet-stream'});
    saveAs(blob, filenames);

  }

  Filename(headers: any) {
    let filenames = '';
    var RGX_FILENAME = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
    const contentDisposition = headers.get('Content-Disposition');
    const matches = RGX_FILENAME.exec(contentDisposition);
    if (matches && matches[1]) {
      filenames = matches[1].replace(/['"]/g, '');
    }
    return filenames;
  }

这是我的 .service :

async download(param: any): Promise<any> {
    const query = this.paramFile(param);
    const result = await this.get(
      `${environment.apiUrl}/file/${query}`
    );
    return result;
  }

  paramFile(param: any) {
    const query = `${param}`;
    return query;
  }

求你帮忙,截止日期是2小时,所以希望有人能帮助我并指导我完成

标签: angular

解决方案


只需调用您的服务,该服务基本上应该返回字节数组,然后以这种方式将其保存到 blob。您可以根据需要更改类型。

在你的 ts 中:

this.yourservice.downloadFile().subscribe((resp) => {
        const fileName = resp.headers.get('filename') ? resp.headers.get('filename') : 'file1_' + new Date();
        const data = resp.body;
        this.blob = new Blob([data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        var downloadUrl = window.URL.createObjectURL(data);
        var link = document.createElement('a');
        link.href = downloadUrl;
        link.download = fileName + '.xlsx';
        link.click();
    }, error => {
       console.log("Error downloading the file!!!");

    });

服务代码:

 downloadFile() {
    const headers = new HttpHeaders()
      .set('Accept', 'application/xlsx; charset=utf-8');
    const url = `${this.baseUrl}dowmloadxls`;
    const params = new HttpParams()
      .set("userId", userId);
    return this.http.get(url, { params, headers, observe: 'response', responseType: 'blob' });
  }

推荐阅读