您的位置:

使用Element上传限制文件类型的方法

一、设置限制文件类型

通过Element的el-upload组件设置限制文件类型,只有特定的文件才能被上传。

<el-upload
  :auto-upload="false"
  :on-change="handleChange"
  :before-upload="handleBeforeUpload"
  :file-list="fileList"
  :accept="acceptType"
  :action="uploadUrl">
  <el-button slot="trigger" type="primary">选取文件</el-button>
  <el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上传到服务器</el-button>
</el-upload>

其中,acceptType就是限制的文件类型,可以是字符串,表示只允许一种类型,比如'image/jpeg';也可以是数组,表示允许多种类型,比如['image/jpeg', 'image/png'];

二、设置提示信息

当上传的文件类型不符合要求时,需要给用户以相应的提示信息。

<el-upload
  :auto-upload="false"
  :on-change="handleChange"
  :before-upload="handleBeforeUpload"
  :file-list="fileList"
  :accept="acceptType"
  :action="uploadUrl">
  <el-button slot="trigger" type="primary">选取文件</el-button>
  <el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上传到服务器</el-button>
  <div slot="tip" class="el-upload__tip">只能上传{{acceptType}}格式的文件</div>
</el-upload>

在el-upload组件中,使用slot="tip"来设置提示信息,在其中加入class="el-upload__tip"使提示信息显示为红色字体。

三、限制文件大小

除了限制文件类型,还可以通过设置最大文件大小来限制文件的上传。

<el-upload
  :auto-upload="false"
  :on-change="handleChange"
  :before-upload="handleBeforeUpload"
  :file-list="fileList"
  :accept="acceptType"
  :action="uploadUrl"
  :before-upload="beforeAvatarUpload">
  <el-button slot="trigger" type="primary">选取文件</el-button>
  <el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上传到服务器</el-button>
  <div slot="tip" class="el-upload__tip">只能上传{{acceptType}}格式的文件,且大小不能超过{{maxSize/1024/1024}}MB</div>
</el-upload>

其中,beforeAvatarUpload是上传前的回调函数,对于超过限制大小的文件进行筛选。

四、完整代码示例

<template>
  <div class="upload-demo">
    <el-upload
      :auto-upload="false"
      :on-change="handleChange"
      :before-upload="beforeAvatarUpload"
      :file-list="fileList"
      :accept="acceptType"
      :action="uploadUrl">
      <el-button slot="trigger" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上传到服务器</el-button>
      <div slot="tip" class="el-upload__tip">只能上传{{acceptType}}格式的文件,且大小不能超过{{maxSize/1024/1024}}MB</div>
      <el-progress :percentage="uploadPercentage" v-if="showProgress"></el-progress>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],  //上传的文件列表
      acceptType: ['jpg', 'jpeg', 'png'],  //限制的文件类型
      maxSize: 20 * 1024 * 1024,  //限制的文件大小,单位是字节
      uploadUrl: '',  //上传的接口
      showProgress: false,  //是否展示上传进度条
      uploadPercentage: 0,  //上传进度百分比
    };
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    beforeAvatarUpload(file) {
      const isJPG = this.acceptType.indexOf(file.type.split('/')[1]) !== -1;
      const isLtSize = file.size / 1024 / 1024 < this.maxSize / 1024 / 1024;
      if (!isJPG) {
        this.$message.error('只能上传' + this.acceptType.join(',') + '格式的文件!');
      }
      if (!isLtSize) {
        this.$message.error('上传文件大小不能超过' + this.maxSize / 1024 / 1024 + 'MB!');
      }
      return isJPG && isLtSize;
    },
    submitUpload() {
      this.showProgress = true;
      var formData = new FormData();
      formData.append("file", this.fileList[this.fileList.length - 1].raw);
      const config = {headers: {'Content-Type': 'multipart/form-data'}};
      axios.post(this.uploadUrl, formData, config)
        .then(response => {
          this.showProgress = false;
          this.uploadPercentage = 0;
          this.$message({
            message: '上传成功',
            type: 'success'
          });
        })
        .catch(error => {
          console.log(error);
          this.showProgress = false;
          this.uploadPercentage = 0;
          this.$message.error('上传失败');
        });
    }
  }
}
</script>