zoukankan      html  css  js  c++  java
  • 实现点击下载按钮即可将图片另存为到本地

    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);
          }

      }
  • 相关阅读:
    求n的元素的最大最小值
    输出一个集合的所有子集,从长到短
    树的各种操作java
    几个笔试题目总结
    小知识不断补充
    java、C语言实现数组模拟栈
    LearnHowToThink
    Android中的this、Activity、Context等
    Android已上线应用开源分享中(第二季)
    Android已上线应用开源分享中(第一季)
  • 原文地址:https://www.cnblogs.com/funian/p/14009330.html
Copyright © 2011-2022 走看看