Angular导出功能(excel导出功能、文件数据流导出功能、图片的下载导出功能)

Angular导出功能(excel导出功能、文件数据流导出功能、图片的下载导出功能)

场景1:(直接返回网络地址进行导出的excel)

后台返回的是 : “http://192.168.0.188:11570/statics/excel/食材清单.xlsx”
这种url直接导出的下载功能实现:

  downloads(url: string) {
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    function iframeLoad() {
      const win = iframe.contentWindow;
      const doc = win.document;
      if (win.location.href === url) {
        if (doc.body.childNodes.length > 0) {
        }
        iframe.parentNode.removeChild(iframe);
      }
    }
    iframe.src = '';
    document.body.appendChild(iframe)
    setTimeout(function loadUrl() {
      iframe.contentWindow.location.href = url;
    }, 50);
  }

场景2:(返回的是数据流的形式再进行导出的)

后台返回的是 (数据流的形式,如下图) 在这里插入图片描述
这种数据流进行导出的功能实现:

简单讲解一下原理:这种文件数据流的返回值要获取拿到,要先在请求头加入responseType与observe,进行声明指定。再者在拿到该数据流后还要再进行进一步的数据处理才能将其导出

exportEerweima(){
	 var value = new FormData()
     value.append('productClass', this.productClass)//自己的数据封装传参,与导出功能无关
      this._CommonService.postList('/api/goods/downloadBasProductQRCode', value,
	 	//-------------------关键---------------------------
	  {
        responseType: "blob",//指定响应中包含的数据类型,指定response 是一个包含二进制数据的 Blob 对象
        observe: 'response',//要获取到完全的response,在 发起请求时 在option中添加 observe: ‘response’;
      }).subscribe((res: any) => {
        //响应头当中的返回如下
        //content-disposition: attachment;filename=%E7%89%A9%E8%B5%84%E4%BA%8C%E7%BB%B4%E7%A0%81.zip
        var name = res.headers.get('content-disposition')//获取文件名,(后台返回的文件名在响应头当中)
        name = decodeURIComponent(name)//由于中文通常都是乱码,所以需要解码
        name = name.substring(name.indexOf("=") + 1)//数据处理获得名字
        this.downloadFile(res.body, name)//数据流都存在body中
      })
}
//文件数据流有多种类型,需自己明确好
downloadFile(data, name) {
    // ContenType类型大全
    // .doc                          application/msword
    // .docx                         application/vnd.openxmlformats-officedocument.wordprocessingml.document
    // .rtf                          application/rtf
    // .xls                          application/vnd.ms-excel application/x-excel
    // .xlsx                         application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    // .ppt                          application/vnd.ms-powerpoint
    // .pptx                         application/vnd.openxmlformats-officedocument.presentationml.presentation
    // .pps                          application/vnd.ms-powerpoint
    // .ppsx                         application/vnd.openxmlformats-officedocument.presentationml.slideshow
    // .pdf                          application/pdf
    // .swf                          application/x-shockwave-flash
    // .dll                          application/x-msdownload
    // .exe                          application/octet-stream
    // .msi                          application/octet-stream
    // .chm                          application/octet-stream
    // .cab                          application/octet-stream
    // .ocx                          application/octet-stream
    // .rar                          application/octet-stream
    // .tar                          application/x-tar
    // .tgz                          application/x-compressed
    // .zip                          application/x-zip-compressed
    // .z                            application/x-compress
    // .wav                          audio/wav
    // .wma                          audio/x-ms-wma
    // .wmv                          video/x-ms-wmv
    // .mp3 .mp2 .mpe .mpeg .mpg     audio/mpeg
    // .rm                           application/vnd.rn-realmedia
    // .mid .midi .rmi               audio/mid
    // .bmp                          image/bmp
    // .gif                          image/gif
    // .png                          image/png
    // .tif .tiff                    image/tiff
    // .jpe .jpeg .jpg               image/jpeg
    // .txt                          text/plain
    // .xml                          text/xml
    // .html                         text/html
    // .css                          text/css
    // .js                           text/javascript
    // .mht .mhtml                   message/rfc822
  
    const contentType = "application/x-zip-compressed";
    const blob = new Blob([data], { type: contentType });
    const url = window.URL.createObjectURL(blob);
    // 打开新窗口方式进行下载
    // window.open(url); 

    // 以动态创建a标签进行下载
    const a = document.createElement("a");
    a.href = url;
    a.download = name;
    a.click();
    window.URL.revokeObjectURL(url);
  }

场景3:下载/导出图片功能

后台返回一个图片的网络路径:“http://192.168.0.188:11570/statics/qrcode/1639281121551-1-1.png”
要求进行导出下载功能

 downloadIamge(fileUrl: any, fileName: any) {
    console.log("fileUrl:",fileUrl)//图片路径   
    //fileUrl: http://192.168.0.188:11570/statics/qrcode/1639281121551-1-1.png
    console.log("fileName:",fileName)//图片名字
    //fileName: http://192.168.0.188:11570/statics/qrcode/1639281121551-1-1.png
    // 获取文件扩展名
    const index = fileUrl.lastIndexOf('.');
    const fileExtension = fileUrl.substring(index + 1);
    // 图片下载
    if (/^image[jpeg|jpg|png|gif]/.test(fileExtension)) {
      const image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        const url = canvas.toDataURL(fileUrl); // 得到图片的base64编码数据
        const a = document.createElement('a'); // 生成一个a元素
        const event = new MouseEvent('click'); // 创建一个单击事件
        a.download = fileName; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = fileUrl;
    } else {
      const elemIF = document.createElement('iframe');
      elemIF.src = fileUrl;
      elemIF.style.display = 'none';
      document.body.appendChild(elemIF);
      setTimeout(() => {
        document.body.removeChild(elemIF);
      }, 1000);
    }
  }

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>