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


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

      }
  • 相关阅读:
    端模板引擎
    Orcale Function Sequence
    OData 集成
    validate[.unobtrusive]和Bootstrap实现tooltip错误提示
    Django
    Web Api 控制器
    HelloWorld和数据绑定
    动态Web Api层
    用户管理
    Docker
  • 原文地址:https://www.cnblogs.com/funian/p/14009330.html
Copyright © 2020-2023  润新知