angular-post请求实现文件下载

  • Post author:
  • Post category:其他


通常情况下,一般使用GET请求进行文件下载,但是存在参数过长,不得不使用POST请求的情况,例如:列表页对选中条目进行下载,但是情况特殊,参数需要传递条目所有信息,而不是id。


使用Blob

  • http请求使用blob的返回类型,
  • 获取文件流后,对数据进行Blob,
  • 再提交给浏览器进行识别下载。
 export(){
      let array:any = [...this.setOfCheckedId];
      let sendMap = array.map(id => {
        let mapList = this.listOfData.find(item=>item.id === id)
        return {...mapList};
      });
      this.service.exportFile(sendMap).subscribe(val=>{
        this.downloadFile(val);
      },err=>{
        console.log(err)
      })
    }
    downloadFile(data) {
      // 下载类型 xls
      const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      // 下载类型:csv
      const contentType2 = 'text/csv';
      const blob = new Blob([data], { type: contentType });
      const url = window.URL.createObjectURL(blob);
      // 打开新窗口方式进行下载
      //window.open(url); 
    
      // 以动态创建a标签进行下载
      const a = document.createElement('a');
      const fileName = new Date().getTime();
      a.href = url;
      a.download = fileName + '.xlsx';
      a.click();
      window.URL.revokeObjectURL(url);
    }
exportFile(data): Observable<any> {
        const url = `xxx/xxx/xxx`;
        return this.http.post(url,data,{responseType: 'arraybuffer'})//此处注意添加responseType,否则请求返回error
          .pipe(
            map(res => {
              return res;
            })
          )
}



版权声明:本文为gaiery原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。