实现点击下载按钮即可将图片另存为到本地

html页面: 

<eui-linkbutton iconCls="fa fa-arrow-circle-down" btnCls="linked-btn"  (click)='downloadFile(fileUrl, fileName)'>下载</eui-linkbutton>
 
JS端:
  // 图片下载
    downloadFile(fileUrl: any, fileName: any) {
      if ( this.downImagePath === '' || this.downImagePath === null) {
        super.alert('请选中一张照片进行下载');
        return;
      }
      fileUrl = this.downImagePath;
      fileName = this.downImagePath;
      // 获取文件扩展名
      const index = fileUrl.lastIndexOf('.');
      const fileExtension = fileUrl.substring(index + 1, fileUrl.length);

    // 图片下载
    downloadFile(fileUrl: any, fileName: any) {
      if ( this.downImagePath === '' || this.downImagePath === null) {
        super.alert('请选中一张照片进行下载');
        return;
      }
      fileUrl = this.downImagePath;
      fileName = this.downImagePath;
      // 获取文件扩展名
      const index = fileUrl.lastIndexOf('.');
      const fileExtension = fileUrl.substring(index + 1, fileUrl.length);

      // 图片下载
      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 || 'photo'; // 设置图片名称
              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);
      }

  }
posted @ 2020-11-20 09:45  孤舟蓑笠翁·  阅读(393)  评论(0编辑  收藏  举报