上传文件前大小和文件类型限制

144 阅读1分钟
// 一个vue页面中存在多个上传文件 但是上传 删除等想调用一个函数时那么 可以通过传参方式调用
// 如果一个vue中只有一个那么可以使用 :before-upload="limitframNum"
// 注意:before-upload 在 :auto-upload="false"的情况下不起作用 在auto-upload为false时可以使用on-change 
 <el-upload v-show="item.icon== 0" ref="tranferRef" class="upload-demo" :headers="headers" :auto-upload='false' :action="tranactionurl" accept='.xlsx,.csv'
                  :multiple='false' :on-change='(file,fileList)=>changefile(0,file,fileList)' :http-request="(params)=>fileUploads(0,params)" :file-list='filetranList'
                  :on-error='uploaderror' :on-remove="(file,fileList)=>handleRemove(0,file,fileList)">
                  <div class="fileexpot addIcon"></div> 
 </el-upload>
 changefile(val,file,fileList){
      if (fileList.length > 1) {
          fileList.splice(0, 1);
      }
      this.limitframNum(val,file)
      if(val == 0){
        this.tranrequired = fileList
      }else{
        this.reasrequired = fileList
      }
},
limitframNum(val,file){
      this.tolfrom.fileName = file.name
      const isLt1M = file.size / 1024 / 1024 < 10
      var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
      let isJPG
      if (userAgent.indexOf("Safari") > -1) {//判断是否Safari浏览器
        var index= file.name.lastIndexOf(".");
        //获取后缀
        var ext = file.name.substr(index+1)
        //判断是否是图片
        isJPG = ext == 'xlsx' || ext == 'xls' || ext == 'csv'
      }else{
        isJPG = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
      }
      if(!isJPG){
        this.$message.error('请上传Excel、csv格式的文件!')
        if(val == 0){
          this.filetranList =[]
        }else{
          this.filerealList =[]
        }
        
        return false
      }
      if (!isLt1M) {
        if(val == 0){
          this.filetranList =[]
        }else{
          this.filerealList =[]
        }
          this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "error"
          });
          return false
      }
    },