vue +element的上传文件限制文件大小和限制文件类型

element的文件上传的文档中介绍:

参数说明类型
accept接受上传的文件类型(thumbnail-mode 模式下此参数无效)string

下面附上代码

	<el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="onchange"
            :before-upload="beforeAvatarUpload"
            :before-remove="beforeRemove"
            accept=".rar,.zip,.doc,.docx,.pdf"
            multiple
            :limit="3"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">选择附件</el-button>
            <div slot="tip" class="el-upload__tip">
              支持格式:.rar .zip .doc .docx .pdf ,单个文件不能超过20MB
            </div>
          </el-upload>

实际效果

在这里插入图片描述
在这里插入图片描述

说明

这里只设置一个accept 是不可行的,用户还可可以选择所有文件进行上传。

这里可以用on-change进行添加文件的时候进行附加判断,

fileList是上传文件的集合,判断上传文件的file对象的name和size属性判断新添加文件的类型和大小。

代码

//html部分
	<el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="onchange"
            :before-upload="beforeAvatarUpload"
            :before-remove="beforeRemove"
            accept=".rar,.zip,.doc,.docx,.pdf"
            multiple
            :limit="3"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">选择附件</el-button>
            <div slot="tip" class="el-upload__tip">
              支持格式:.rar .zip .doc .docx .pdf ,单个文件不能超过20MB
            </div>
          </el-upload>
//js部分
	  onchange(file,fileList) {
      let fileName = file.name;
      let uid = file.uid
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (
        lastName.toLowerCase() !== ".zip" &&
        lastName.toLowerCase() !== ".rar"&&
        lastName.toLowerCase() !== ".docx"&&
        lastName.toLowerCase() !== ".pdf"
      ) {
        this.$message.error("文件必须为.rar .zip .doc .docx .pdf 类型");
        // this.resetCompressData()
        for(var i = 0;i<fileList.length;i++) {
          if(fileList[i].uid == uid) {
            fileList.splice(i,1)
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt =
        file.size / 1024 / 5 >= 1 && file.size / 1024 / 1024 / 20 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不得小于5KB,不得大于20MB!");
        for(var i = 0;i<fileList.length;i++) {
          if(fileList[i].uid == uid) {
            fileList.splice(i,1)
          }
        }
      }
      return isLt;
    },

此时,上传限制类型和限制大小的上传功能完成

结果展示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
应大哥的诉求,我的代码确实不完整,下面就是整个上传文件的完整代码

 <div class="page">
    <header>
      <span>{{type=='Note'?'我的笔记':'我的资料'}}</span>
      <div class="btns">
        <el-button @click="refresh">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
        <el-button @click="goBack">
          <i class="el-icon-arrow-left"></i>
          返回
        </el-button>
      </div>
    </header>
    <div class="condition">
      <el-row>
        <el-col :span="16">
          <div class="left">
            <div class="condition_item">文件来源</div>
            <div class="condition_item">名称排序</div>
            <div class="condition_item">我的关注</div>
            <div class="condition_item">文件筛选</div>
            <el-input
              placeholder="请输入内容"
              prefix-icon="el-icon-search"
              @keyup.enter.native="onSubmit"
              v-model="value"
            >
            </el-input>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="right" v-if="type=='Data'">
            <el-button @click="NewFolder">
              <i class="el-icon-folder-add"></i>
              新建文件夹</el-button
            >

            <el-button type="primary" @click="newFile">
              <i class="el-icon-tickets"></i>
              新建文件</el-button
            >
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="container">
      <div class="bread" style="height: 50px; line-height: 50px" v-if="type=='Data'">
        <span>全部文件</span>
        <i>/</i>
        <span>全部文件</span>
      </div>
      <div class="head">
        <span> {{type=='Note'?'笔记列表':'数据列表'}} </span>
        <div class="function" v-if="type=='Data'">
          <el-button>
            <i class="el-icon-folder-add"></i>
            分享</el-button
          >
          <el-button>
            <i class="el-icon-tickets"></i>
            下载</el-button
          >
          <el-button>
            <i class="el-icon-star-on"></i>
            关注</el-button
          >

          <el-button>
            <i class="el-icon-download"></i>
            下载</el-button
          >
          <el-button>
            <i class="el-icon-edit-outline"></i>
            重命名</el-button
          >

          <el-button>
            <i class="el-icon-document-copy"></i>
            复制</el-button
          >
          <el-button>
            <i class="el-icon-rank"></i>
            移动</el-button
          >

          <el-button>
            <i class="el-icon-delete"></i>
            删除</el-button
          >
        </div>
      </div>

      <table
        style="
          border-color: rgba(233, 233, 233, 1);
          border-right: none;
          border-bottom: none;
        "
        border="1"
        cellpadding="0"
        cellspacing="0"
        width="100%"
      >
        <tr >
          <td width="5%"><el-checkbox v-model="checked"></el-checkbox></td>
          <td>文件</td>
          <td v-if="!isall&&type=='Data'">文件大小</td>
          <td v-if="isall&&type=='Note'">笔记内容</td>
          <td v-if="!isall&&type=='Data'">文件类型</td>
          <td v-if="isall&&type=='Note'">笔记标签</td>
          <td v-if="!isall&&type=='Data'">文件来源</td>
          <td>更新时间</td>
        </tr>
        <tr v-for="(item,index) in collList" :key="index">
          <td><el-checkbox v-model="checked"></el-checkbox></td>
          <td @click="getInto('in',item.id)" v-if="isall&&type=='Data'">{{item.folderName}}==</td>
          <td @click="getInto(item)" v-if="isall&&type=='Note'">{{item.filetitle}}</td>
          <td v-if="!isall&&type=='Data'">2M</td>
          <td v-if="isall&&type=='Note'">{{item.bookmarkName}}</td>
          <td v-if="!isall&&type=='Data'">.DOC</td>
          <td v-if="isall&&type=='Note'">{{item.kgLabels | renders}}</td>
          <td v-if="!isall&&type=='Data'">个人创建</td>
          <td>{{item.createTime}}</td>
        </tr>
      
      </table>
      <div class="fullPage">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="fullpage.total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog title="新建文件" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules">
        <el-form-item
          label="文件标题"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            v-model="form.name"
            placeholder="请输入文件标题"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件描述" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            placeholder="请输入文件描述"
            v-model="form.desc"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传文件" :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="onchange"
            :before-upload="beforeAvatarUpload"
            :before-remove="beforeRemove"
            accept=".rar,.zip,.doc,.docx,.pdf"
            multiple
            :limit="3"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">选择附件</el-button>
            <div slot="tip" class="el-upload__tip">
              支持格式:.rar .zip .doc .docx .pdf ,单个文件不能超过20MB
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="参与人员" :label-width="formLabelWidth">
          <el-select
            v-model="value2"
            multiple
            collapse-tags
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提醒方式" :label-width="formLabelWidth">
          <el-checkbox-group v-model="form.type">
            <el-checkbox label="站内信" name="type"></el-checkbox>
            <el-checkbox label="邮件" name="type"></el-checkbox>
            <el-checkbox label="信息" name="type"></el-checkbox>
            <span class="mess_num">(短信可用数:1000条)</span>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog title="添加文件夹" :visible.sync="dialogNewFolder">
      <el-form :model="form">
        <el-form-item>
          <el-input
            v-model="folderName"
            placeholder="输入文件夹名称"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNewFolder = false">取 消</el-button>
        <el-button type="primary" @click="dialogNewFolder = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
import {GetCollList,getAllNote,GetMyNote,getNoteSearch} from '../../api/apis'
<script>
import {GetCollList,getAllNote,GetMyNote,getNoteSearch} from '../../api/apis'
export default {
  inject:['reload'],
  data() {
    return {
      currentPage: 1,
      pagesize: 10,
      fullpage: {},
      value: "",
      isall: true,
      checked: false,
      dialogFormVisible: false,
      dialogNewFolder: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      // 当前页面的类型 我的笔记/我的资料
      type:'',
      rules: {
        name: [{ required: true, message: "请输入文件标题", trigger: "blur" }],
      },
      // 文件夹列表
      collList:[],
      folderName: "",
      options: [
        {
          value: "选项1",
          label: "黄金糕",
        },
        {
          value: "选项2",
          label: "双皮奶",
        },
        {
          value: "选项3",
          label: "蚵仔煎",
        },
        {
          value: "选项4",
          label: "龙须面",
        },
        {
          value: "选项5",
          label: "北京烤鸭",
        },
      ],
      value2: [],
      formLabelWidth: "80px",
      fileList: [
        
      ],
    };
  },
  filters:{
      renders(val) {
        if(val){
          var str = ''
          for(var i = 0;i <val.length;i++) {
            str += val[i].labelName+','
          }
          return str.substring(0,str.length-1)
        }
         else {
           return ''
        }
      }
  },
  computed:{

  },
  //生命周期 - 创建完成(访问当前this实例)
  created() {},
  //生命周期 - 挂载完成(访问DOM元素)
  mounted() {
    this.GetcollList()
    if(this.$route.query.type == 'Note') {
      this.type = 'Note'
    }else {
      this.type = 'Data'
    }
  },
  methods: {
    // 输入框回车事件
    onSubmit() {
      // if(this.value=='') {
      //   this.$message.info('请输入关键字')
      // }else
        if(this.type=='Data') {

      }else {
        getNoteSearch({
          KgMarkName: this.value,
          pageNo : this.currentPage,
          pageSize: this.pagesize,
        }).then((res)=>{
          var { data } = res
          if(data.code == 200 ){
            console.log(data)
            if(data.result.records == []) {
              return false
            }
            var result = data.result.records
            for(var i = 0 ;i<result.length;i++) {
              result[i].folderName =  result[i].markFolderName
            }
            this.collList = result
          }else {
            this.$message.error(data.message)
          }
        })
      }
    },
    onchange(file,fileList) {
      let fileName = file.name;
      let uid = file.uid
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (
        lastName.toLowerCase() !== ".zip" &&
        lastName.toLowerCase() !== ".rar"&&
        lastName.toLowerCase() !== ".docx"&&
        lastName.toLowerCase() !== ".pdf"
      ) {
        this.$message.error("文件必须为.rar .zip .doc .docx .pdf 类型");
        // this.resetCompressData()
        for(var i = 0;i<fileList.length;i++) {
          if(fileList[i].uid == uid) {
            fileList.splice(i,1)
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt =
        file.size / 1024 / 5 >= 1 && file.size / 1024 / 1024 / 20 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不得小于5KB,不得大于20MB!");
        for(var i = 0;i<fileList.length;i++) {
          if(fileList[i].uid == uid) {
            fileList.splice(i,1)
          }
        }
      }
      return isLt;
    },
    beforeAvatarUpload(file) {
      let fileName = file.name;
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (
        lastName.toLowerCase() !== ".zip" &&
        lastName.toLowerCase() !== ".rar"&&
        lastName.toLowerCase() !== ".docx"&&
        lastName.toLowerCase() !== ".pdf"
      ) {
        this.$message.error("文件必须为.rar .zip .doc .docx .pdf 类型");
        // this.resetCompressData()
        return;
      }
      // 限制上传文件的大小
      const isLt =
        file.size / 1024 / 5 >= 1 && file.size / 1024 / 1024 / 100 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不得小于5KB,不得大于100MB!");
      }
      return isLt;
    },
    NewFolder() {
      this.dialogNewFolder = true;
    },
    // 新建文件
    newFile() {
      this.dialogFormVisible = true;
    },
    Personal() {
      this.$router.push("/Personal");
    },
    goBack() {
      this.$router.go(-1);
    },
    // 刷新当前页面
    refresh() {
      this.reload()
    },
    Editing() {
      this.$router.push("/Editing");
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.GetcollList()
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.GetcollList()
    },
    // 进入文件夹
    getInto(index,obj) {
      if (index == 'in') {
        this.isall = false;
        if(this.type=='Data') {

        }
      } else {
        this.$router.push({
          path:'/hello',
          query:{
            type:index.datasource,
            id:index.textid,
            name:index.bookmarkId
          }
        });
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    // 获取文件夹
    GetcollList() {
      // 判断是什么类型的页面  Data ---- 我的资料   Note ---- 我的笔记
      if(this.type == 'Data') {
        GetCollList({}).then((res)=>{
          var { data } = res
          if(data.code == 200) {
            this.collList = data.result
          }
        })
      }else {
        GetMyNote({
          pageNo: this.currentPage,
          pageSize :this.pagesize
        }).then((res) => {
          var {data} = res
          if (data.code == 200) {
            var result = data.result.records
            for(var i = 0 ;i<result.length;i++) {
              result[i].folderName =  result[i].markFolderName
            }
            this.collList = result
          }
        })
      }
    }
  },
};
</script>

GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45 7 个月前
a07f3a59 * Update transition.md * Update table.md * Update transition.md * Update table.md * Update transition.md * Update table.md * Update table.md * Update transition.md * Update popover.md 7 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐