vant上传组件通过【before-read】校验大小和格式

            <template #input>
              <van-uploader multiple v-model="item.desc" :before-read="(file)=>beforeRead(file,['jpg','jpeg','png'])" :after-read="(file)=>afterImgRead(file, index)"
                @delete='handleDeleteFile' max-count='5' upload-text='点击上传' accept=".jpg, .jpeg, .png" />
            </template>


            <template #input>
              <van-uploader multiple v-model="item.desc" :before-read="(file)=>beforeRead(file,['pdf', 'doc', 'docx', 'xls', 'xlsx'])"
                :after-read="(file)=>afterFileRead(file, index)" max-count='5' upload-text='点击上传' accept=".pdf, .doc, .docx, .xls, .xlsx" />
            </template>
    // 上传图片、上传文件校验大小和格式
    beforeRead(file, correctFormat) {
      const isArray = Object.prototype.toString.call(file) === '[object Array]'
      const isLimit50M = 1024 * 1024 * 50 // 是否大于50M
      const isImg = correctFormat + '' === ['jpg', 'jpeg', 'png'] + ''
      if (isArray) {
        const sizes = file.map(item => item.size)
        if (sizes.some(item => item > isLimit50M)) {
          this.$vux.toast.text('大小不能超过50M')
          return false
        }
        const types = file.map(
          ({ name }) => name.slice(name.lastIndexOf('.') + 1) // 后缀
        )
        if (!types.every(item => correctFormat.includes(item))) {
          this.$vux.toast.text(
            isImg ? '请上传jpg/jpeg/png' : '请上传pdf/word/excel'
          )
          return false
        }
      } else {
        if (file.size > isLimit50M) {
          this.$vux.toast.text('大小不能超过50M')
          return false
        }
        const type = file.name.slice(file.name.lastIndexOf('.') + 1)
        if (!correctFormat.includes(type)) {
          this.$vux.toast.text(
            isImg ? '请上传jpg/jpeg/png' : '请上传pdf/word/excel'
          )
          return false
        }
      }
      return true
    }

 

上一篇:Vant 登录发起axios等待动画结束


下一篇:H5+Vant 上传文件