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 { 
      // 图片移除逻辑
    }
  };
    原文作者:See you
    原文地址: https://blog.csdn.net/Mine____/article/details/109508862
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞