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 {
          // 图片移除逻辑
        }
      };
    
  • 相关阅读:
    [Kotlin] Open Classes and Inheritance
    [Kotlin] Class
    [Kotlin] Reverse a List with downTo
    [Kotlin] Named loop
    [Kotlin] for loop
    [Kotlin] Array List ArrayList
    深度解读 java 线程池设计思想及源码实现
    源码实战 | 从线程池理论聊聊为什么要看源码
    自己实现一个简单的线程池
    死磕 java线程系列之自己动手写一个线程池(续)
  • 原文地址:https://www.cnblogs.com/Mine-/p/14098586.html
Copyright © 2011-2022 走看看