vue + element + image-conversion 上传图片压缩并限制尺寸大小

1、 先安装 image-conversion 插件

npm i image-conversion --save

2、写一个公共的混入方法

import * as imageConversion from 'image-conversion';
export default {
    data() {
        return {

        }
    },
    mounted() {


    },
    methods: {
        compressorImg(file) {
            return new Promise(resolve => {
                imageConversion.compressAccurately(file, 100).then(res => {
                    console.log(res);
                    let files = new File([res], file.name, { type: file.type });
                    resolve(files)
                })
            });
        },
    },
    computed: {

    }
}

3、vue组件调用

<el-upload
       ref="upload"
         class="upload-demo"
         action="#"
         accept=".JPG,.JPEG,.PNG"
         :http-request="beforeAvatarUpload2"
         :show-file-list="false"
         :limit="1"
         drag
       >
         <i class="el-icon-upload"></i>
         <div class="el-upload__text">
           将文件拖到此处,或<em>点击上传</em>
         </div>
         <div class="el-upload__tip" slot="tip">
           只能上传jpg/png图片,尺寸340*86px以内,不超过2MB
         </div>
  </el-upload>
import public_mixin from "@/utils/mixin/public_mixin";
export default {
  mixins: [public_mixin],
  data() {
    return {
      imageUrl: "",
      uploadAction: "",
      sendData: new FormData(),
    };
  },
  methods: {
  	async beforeAvatarUpload2(file) {
      const self = this;
      let subFile = await this.compressorImg(file.file);
      file.file = subFile;
      this.imgchecked(file, 340, 86)
        .then((res) => {
          if (!res) {
            self.$message.warning(`请上传 340*86 px 的图片!`);
            self.$refs.upload.clearFiles();
            return false;
          } else {
            self.beforeAvatarUpload(file, 2);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //判断尺寸方法
    imgchecked(file, wdh, hgt) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file.file); // 必须用file.raw
        reader.onload = () => {
          // 让页面中的img标签的src指向读取的路径
          let img = new Image();
          img.src = reader.result;

          img.onload = () => {
            if (img.width !== wdh || img.height != hgt) {
              resolve(false);
            } else {
              resolve(true);
            }
          };
        };
      });
    },
    async beforeAvatarUpload(file, type) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log(file);
      if (!isJPG) {
        this.$message.error("上传logo图片只能是 JPG或者 PNG 格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("上传logo图片大小不能超过 2MB!");
        return;
      }
      await this.uploadSectionFile(file, type);
      return isJPG && isLt2M;
    },
    //服务器获取签名
    async uploadSectionFile(file, type) {
      let fileObj = file;
      let response = await this.$post("X/UploadToken", {
        filetype: "upload_image",
      });
      if (response.code == "10000") {
        let json = response.results;
        //上传地址
        // this.uploadAction = json.host.replace('-internal', '');
        this.filename = new Date().getTime() + ("." + file.name.split(".")[1]);
        this.sendData.append("OSSAccessKeyId", json.accessid);
        this.sendData.append("policy", json.policy);
        this.sendData.append("Signature", json.signature);
        this.sendData.append("keys", json.dir);
        this.sendData.append("key", json.dir + this.filename);
        this.sendData.append("callback", json.callback);
        this.sendData.append("success_action_status", 200); // 指定返回的状态码
        this.sendData.append("type", fileObj.type);
        this.sendData.append("file", fileObj);
        let imageUrl =
          json.host.replace("-internal", "") + "/" + json.dir + this.filename; // 上传后的文件地址
        await this.uploadToOur(
          json.host.replace("-internal", ""),
          imageUrl,
          type
        );
        this.tools.httpDialog(1, "上传成功");
      } else {
        this.tools.httpDialog(0, response.message);
      }
    },
    //上传文件
    async uploadToOur(ossUrl, imageUrl, type) {
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      try {
        await axios.post(ossUrl, this.sendData, config);
        this.sendData = new FormData();
        console.log(type, "type", imageUrl, "imageUrl");
      } catch (error) {
        console.log(error);
      }
    },
  },
};

3、部分显示效果如下:
vue + element + image-conversion 上传图片压缩并限制尺寸大小_第1张图片

你可能感兴趣的:(vue.js,javascript,前端)