input 框上传多个文件以及做文件校验

  • Post author:
  • Post category:其他


1、如何上传多个文件

在input标签中加入 multiple 属性

<input type="file" class="input" ref="input" multiple />
//或者
<input type="file" class="input" ref="input" multiple="multiple" />

2、如何进行文件校

const allowTypes = [
        "image/jpeg",
        "image/png",
        "image/x-png",
        "image/bmp",
        "image/gif",
      ] //允许上传的文件类型
      const maxFileSize = 50 * 1024 * 1024 //允许上传的单个文件的大小限制,最大能上传50M

//forEach无法通过正常流程(如break)终止循环,但可通过抛出异常的方式实现终止循环
//目的是为了提高性能

      try {
        this.$refs.input.files.forEach((item) => {
          const fileName = item.name //文件名
          const fileType = item.type //文件类型
          const fileSize = item.size //文件大小,单位为byte(字节)
//includes()放法,判断数组中是否含有这个字符串
          if (!allowTypes.includes(fileType)) {
            this.$message.error(fileName + "不是图片,只能上传图片!")
            throw new Error("End Loop")
          }
          if (fileSize > maxFileSize) {
            this.$message.error(fileName + "的文件大小超出了50M限制")
            throw new Error("End Loop")
          }
        })
      } catch (e) {
        if (e.message === "End Loop") throw e
//注意:在catch语句块中加了if(e.message === 'End Loop') throw e这句代码会在控制台报一个错误,这个错误是try语句块中抛出的

如果不想看到这个报错,将if(e.message === 'End Loop') throw e这一句删除就行
      }




版权声明:本文为weixin_66591252原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。