• antd upload 图片上传前压缩


      onChange = (files, type, index) => {
    
        const newItem = _.cloneDeep(this.state.imgData);
        if (type === "add") {
          const file = [...files].pop().file;
          const newitem = [...files].pop(); // 多次上传之前的数据
          const handle = this.handleUPdata; // 图片上传接口
          
          // 限制上传十兆以上图片
          if (file.size > 10 * 1024 * 1024) {
            Toast.fail("请上传10M以下的图片!");
            return;
          }
          // 更新状态
          this.setState({
            files,
            loading: true,
          });
          // 压缩一兆以上图片
          if (file.size > 1 * 1024 * 1024) {
            let rate = 0.2;
            let reader = new FileReader();
            reader.readAsDataURL(file);
            let img = new Image();
            reader.onload = function (e) {
              img.src = e.target.result;
            };
            img.onload = function () {
              let canvas = document.createElement("canvas");
              let context = canvas.getContext("2d");
              // 文件大小KB
              const fileSizeKB = Math.floor(file.size / 1024);
              // console.log('file size:', fileSizeKB, 'kb');
              // 配置rate和maxSize的关系
              if (fileSizeKB * rate > 3027) {
                rate = Math.floor((3027 / fileSizeKB) * 10) / 30;
                }
              // 缩放比例,默认0.5
              let targetW = (canvas.width = this.width * rate);
              let targetH = (canvas.height = this.height * rate);
              context.clearRect(0, 0, targetW, targetH);
              context.drawImage(img, 0, 0, targetW, targetH);
              canvas.toBlob((blob) => {
                const newImage = new File([blob], file.name, {
                  type: file.type,
                });
                // console.log(newImage.size / 1024, "kb");
                // 图片上传接口
                handle([{ file: newImage }]);  
              });
            };
          } else {
            // 图片没有超限则直接上传
            handle(files);// 图片上传接口
          }
        } else {
          // 图片移除逻辑
        }
      };
    
  • 相关阅读:
    如何用ST-LINK给STM32下载HEX文件
    快恢复二极管和肖特基二极管的区别和是否能够替代使用?
    Python环境变量配置
    IAP笔记
    如何将24位RGB颜色转换16位RGB颜色
    内网外网同时使用
    bootstraptable 服务端分页问题
    weblogic奇葩问题
    SSM框架
    java通过poi操作excel
  • 原文地址:https://www.cnblogs.com/Mine-/p/14098586.html
Copyright © 2020-2023  润新知