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

      }
  • 相关阅读:
    hdu 5534(dp)
    hdu 5533(几何水)
    hdu 5532(最长上升子序列)
    *hdu 5536(字典树的运用)
    hdu 5538(水)
    假如数组接收到一个null,那么应该怎么循环输出。百度结果,都需要提前判断。否则出现空指针异常。。我还是想在数组中实现保存和输出null。
    第一个登录页面 碰到的疑问
    浅谈堆和栈的区别
    Java中的基础----堆与栈的介绍、区别
    JS的Document属性和方法
  • 原文地址:https://www.cnblogs.com/funian/p/14009330.html
Copyright © 2011-2022 走看看