如何在Angle CLI中下载文件? [英] How to download file in angular cli?

查看:47
本文介绍了如何在Angle CLI中下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem when downloading a file, when I get a response from the backend how do I download the file?

错误是我想获取文件名

这是我的.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:

this my .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个小时,所以我希望有人可以帮助我并指导我结束

I beg for your help, the deadline is 2 hours, so I hope someone can help me and guide me to the end

推荐答案

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

Just call your service which should basically return the byte array and then save it to the blob in this way. You can chnage the type as required.

在您的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' });
  }

这篇关于如何在Angle CLI中下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆