• 【angular5项目积累总结】文件下载


    download() {
    
    
    const token = localStorage.getItem('token');
    
    
    let headers: HttpHeaders = new HttpHeaders();
    
    
    headers = headers
    
    .set('Authorization', 'Bearer ' + token);
    
    const url = 'http://localhost:8764/api/v1/user/downLoadZipFile';
    
    
    this.http.get(url, {headers: headers, observe: 'response', responseType: 'blob'}).subscribe(response => {
    
    
    console.log(response);
    
    
    console.log(response.headers.keys());
    
    
    this.downloadFile(response);
    
    }, (error: HttpErrorResponse) => {
    
    
    console.log(error.error);
    
    });
    
    }
    
    
    
    downloadFile(data: HttpResponse<Blob>) {
    
    
    const file = new Blob([data.body], {type: 'application/zip'});
    
    
    const a = document.createElement('a');
    
    
    a.id = 'tempId';
    
    document.body.appendChild(a);
    
    
    a.download = 'haha.zip';
    
    
    a.href = URL.createObjectURL(file);
    
    
    a.click();
    
    
    const tempA = document.getElementById('tempId');
    
    
    if (tempA) {
    
    
    tempA.parentNode.removeChild(tempA);
    
    }
    
     
    
    }
    
    }
    var blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});  
    var objectUrl = URL.createObjectURL(blob);  
    var a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display:none');
    a.setAttribute('href', objectUrl);
    a.setAttribute('download', fileName);
    a.click();
    URL.revokeObjectURL(objectUrl); 

    通用下载代码JS:

     downloadFile(filePath: any) {
        this.meetingService.downloadFile(filePath, rtv => {
          if (rtv) {
            let _blob = new Blob([rtv]);
            let _filename = filePath.substring(filePath.lastIndexOf('_') + 1);
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(_blob, _filename);
            } else {
              let _link = document.createElement('a');
              let _url = window.URL.createObjectURL(_blob);
              document.body.appendChild(_link);
              _link.setAttribute('style', 'display:none');
              _link.href = _url;
              _link.download = _filename;
              _link.click();
              window.URL.revokeObjectURL(_url);
              _link.remove();
            }
          } else {
            alert('下载失败,请稍后重试!');
          }
        });
      }

    参考文章:

    https://www.cnblogs.com/liugang-vip/p/7016733.html

  • 相关阅读:
    设计模式-解释器模式
    安卓运行环境(四)
    安卓创建应用窗口(三)
    微型 ORM 的第二篇 DapperLambda性能测试[Dapper比较篇]
    微型 ORM 的第一篇 DapperLambda发布
    visual studio 2013 使用IIS Express附加调试MVC5
    数据库常用查询语句写法(优化)
    Windows Server 2008通过计划任务定时执行bat文件
    第一章 Memcached安装
    第四章 LINQ to SQL基本用法
  • 原文地址:https://www.cnblogs.com/sybboy/p/9214094.html
Copyright © 2020-2023  润新知