el-upload上传的图片进行压缩

本文介绍了如何在前端使用Vue.js中的ElementUI组件`el-upload`实现文件上传前,进行图片格式检查和压缩的JavaScript代码,确保上传的是JPEG、GIF、JPG等格式的图片并限制大小。
摘要由CSDN通过智能技术生成

直接上代码

<el-upload
  :before-upload="onBeforeUpload"
>

js

 onBeforeUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/gif" ||
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/GIF" ||
        file.type === "image/JPG" ||
        file.type === "image/bmp";
      if (!isJPG) {
        this.$message.error("图片格式不正确!");
        return false;
      }
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          const img = new Image();
          img.src = e.target.result;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = 110; // 设置压缩后图片的宽度
            canvas.height = 110; // 根据原始图片比例计算压缩后图片的高度
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            canvas.toBlob((blob) => {
              const compressedFile = new File([blob], file.name, { type: file.type, lastModified: Date.now() });
              resolve(compressedFile);
            }, file.type);
          };
        };
      });
    },
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值