element-ui文件上传 做类型大小的限制

日期:2018年12月16日 阅读次数:4983 分类:Vue

方法一:用文件类型(filettype)判断

<el-upload
  class="avatar-uploader"
  action="https://jsonplaceholder.typicode.com/posts/"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

export default {
  data() {
    return {
      imageUrl: ''
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

 

方法二:使用文件名(file.name)的后缀名判断【推荐】

<div class="filebox">
    <el-upload class="upload-demo" multiple
    :action="url"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :limit="limitnum"
    :on-exceed="handleExceed"
    :file-list="fileList"
    :beforeUpload="beforeAvatarUpload">
        <el-button size="mini" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
</div>

methods里面写beforeAvatarUpload这个方法

methods :{
  beforeAvatarUpload(file) {
    var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
    const extension = testmsg === 'xls'
    const extension2 = testmsg === 'xlsx'
    const isLt2M = file.size / 1024 / 1024 < 10
    if(!extension && !extension2) {
      this.message({
          message: '上传文件只能是 xls、xlsx格式!',
          type: 'warning'
      });
    }
    if(!isLt2M) {
      this.message({
          message: '上传文件大小不能超过 10MB!',
          type: 'warning'
      });
    }
    return extension || extension2 && isLt2M
  }
}

想要什么限制加什么限制就好。

来源:
https://blog.csdn.net/lianxin19900610/article/details/81184773
https://blog.csdn.net/qq_21423689/article/details/78803701

文章标签: