zoukankan      html  css  js  c++  java
  • 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 {
          // 图片移除逻辑
        }
      };
    
  • 相关阅读:
    移动开发 Native APP、Hybrid APP和Web APP介绍
    urllib与urllib2的学习总结(python2.7.X)
    fiddler及postman讲解
    接口测试基础
    UiAutomator2.0 和1.x 的区别
    adb shell am instrument 命令详解
    GT问题记录
    HDU 2492 Ping pong (树状数组)
    CF 567C Geometric Progression
    CF 545E Paths and Trees
  • 原文地址:https://www.cnblogs.com/Mine-/p/14098586.html
Copyright © 2011-2022 走看看