文件下载方法

    downloadFile(fileName:string,filePath:string){
        this.service.downloadFile(filePath).subscribe(file=>{
            const blobUrl = URL.createObjectURL(file); // 创建下载链接
            const a = document.createElement('a');
            a.href = blobUrl;
            a.target = '_parent';
            a.download = fileName ;
            (document.body || document.documentElement).appendChild(a);
            a.click();
            a.remove();
        })
    }

文件下载接口

  downloadFile(filePath) {
    const htppOptionsPipe = this.fileHeaders
      .append('session', this.getUserSession())
      .append('traceid', 'PC' + new Date().getTime());
    return this.http.get(
      dataUrl + `/api/civilcrm/user/downloadfile?fileName=${filePath}`,
      { headers: htppOptionsPipe, responseType: 'blob' }
    );
  }

如果下载的文件后缀浏览器不识别,可以采用以下的方法处理,仅供参考

  // 下载文件
  downloadFile(fileName:string,filePath:string){
    this.service.downloadFile(filePath).subscribe(file=>{
      const blob = new Blob([file],{type: 'application/octet-stream'})
      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = blobUrl;
      a.target = '_parent';
      a.download = `${fileName}.lrmx` ; // 在这里补充了文件的后缀名
      (document.body || document.documentElement).appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(blobUrl) // 释放blob对象
    })
  }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐