element-upload 自定义上传、限制文件大小、格式以及图片尺寸

本文档详细介绍了如何在Element-Upload组件基础上,实现对上传图片的格式、大小和尺寸限制,并自定义上传过程,以便携带用户信息。通过实例展示了如何检查文件类型、大小和尺寸,以及如何控制上传按钮的显示和隐藏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

element-upload 自定义上传、限制文件大小、格式以及图片尺寸

1. 前言

前段时间业务上有个需求是前端上传 png 格式 100kb 以内并且 尺寸为 80px * 50px 的图片,同时在上传的同时需要携带用户的个人信息以及其他额外信息。

因此在 element-upload 基础之上,实现这个需求需要在上传前检查图片的大小,格式以及尺寸,同时,需要自定义上传而不是使用组件的 action 上传方式, 因为需要携带额外参数。

2. 完整实现示例

<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      :limit="limitNum"
      :class="{hide:hideUploadEdit}"
      :on-remove="handleRemove"
      :on-change="handleEditChange"
      :http-request="handleUpload"
      :before-upload="uploadPreview"
      :with-credentials="true" 
      :auto-upload="true" 
      accept=".png" 
      action=""
      list-type="picture-card"
      :file-list="fileList"
    >
      <i slot="trigger" class="el-icon-plus"></i>
    </el-upload>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      hideUploadEdit: false, // 隐藏'上传按钮'
      limitNum: 1, // 图片数量
      fileList: [] // 图片列表
    };
  },
  methods: {
    handleEditChange(file, fileList) {
      this.hideUploadEdit = fileList.length >= this.limitNum;
      console.log("this.fileList:", this.fileList);
      console.log("this.hideUploadEdit:", this.hideUploadEdit);
    },

        uploadPreview(file) {
      const isPNG = /^.png$/.test(file.name.substring(file.name.lastIndexOf('.')));
      const isLt100KB = file.size / 1024  < 100;

      if (!isPNG) {
        this.$message.error("上传图片只能是 PNG 格式!");
        return false;
      };
      if (!isLt100KB) {
        this.$message.error("上传图片大小不能超过 80KB!");
        return false;
      };
      
      let is80x56 = true;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (theFile) => {
        const image = new Image();
        image.src = theFile.target.result;
        image.onload = () => {
          const { width, height } = image;
          if(width !== 80 || height !== 56) {
            this.$message.error("请上传 80*56 px 的图片!");
            is80x56 = false;
          };
        };
      };
      return isPNG && isLt100KB && is80x56;
    },

    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.fileList = [];
      } else {
        let dl = this.fileList.indexOf(file);
        this.fileList.splice(dl, 1);
      }
      this.hideUploadEdit = fileList.length >= this.limitNum;
    },

    uploadPreview(file) {
      const isPNG = /^.png$/.test(file.name.substring(file.name.lastIndexOf('.')));
      const isLt100KB = file.size / 1024  < 100;

      if (!isPNG) {
        this.$message.error("上传图片只能是 PNG 格式!");
        return false;
      };
      if (!isLt100KB) {
        this.$message.error("上传图片大小不能超过 80KB!");
        return false;
      };
      
      let is80x56 = true;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (theFile) => {
        const image = new Image();
        image.src = theFile.target.result;
        image.onload = () => {
          const { width, height } = image;
          if(width !== 80 || height !== 56) {
            this.$message.error("请上传 80*56 px 的图片!");
            is80x56 = false;
          };
        };
      };
      return isPNG && isLt100KB && is80x56;
    },

    handleUpload(param) {
      this.param = param;
      // 这里可以进行上传
      // let formData = new FormData(); //formdata格式
      // formData.append("fileName", this.param.file);
      // 将formData 作为 body 上传即可, 有额外的参数可携带
    },

    submitUpload() {
      if (!this.param) {
        this.$message("请选择图片");
      } else {
        let formData = new FormData(); //formdata格式
        formData.append("file", this.param.file);
        // 也可以在这里进行上传
        // let formData = new FormData(); //formdata格式
        // formData.append("fileName", this.param.file);
        // 将formData 作为 body 上传即可, 有额外的参数可携带
      }
    },
  }
};
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}
.el-upload-list__item {
  transition: none !important;
}
</style>
### element-ui 中设置图片上传限制 #### 文件大小和类型的限制 为了实现文件大小和类型的限制,在 `el-upload` 组件中可以通过 `before-upload` 属性来定义一个函数,该函数会在每次文件上传前被调用。在这个函数内部可以编写逻辑来验证文件类型以及检查文件大小。 ```javascript // JavaScript 函数用于在上传之前执行自定义校验 function beforeAvatarUpload(file) { const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPGorPNG) { this.$message.error('仅支持 JPG 和 PNG 格式图片!'); } if (!isLt2M) { this.$message.error('图片大小不得超过 2MB!'); } return isJPGorPNG && isLt2M; } ``` 此代码片段展示了如何利用 `before-upload` 来控制允许上传的文件格式为 `.jpg`, `.jpeg`, 或者`.png` 并且最大尺寸不超过2 MB[^2]。 #### HTML 配置 在HTML部分,则需确保 `<el-upload>` 的标签内包含了上述提到的相关属性: ```html <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :before-upload="beforeAvatarUpload"> </el-upload> ``` 这里设置了 `class`、`action`(指定服务器端接收请求地址),并绑定了 `before-upload` 到前面创建好的方法上。 #### 处理其他事件 除了基本的文件筛选外,还可以监听更多有用的回调事件比如 `on-exceed` 当超出数量上限时触发;`on-success` 成功完成一次上传之后触发;`on-remove` 用户手动移除某个已选文件时触发等。这些功能可以帮助构建更加完善可靠的用户体验[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangpaopao0609

看星空看日落不如看我的眼眸

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值