• Ajax
  • Ant design
  • Axios-Fetch
  • Avue
  • Browser
  • Canvas
  • CSS
  • Dos-bat
  • Dva
  • Dedecms
  • Echart
  • ElementUI
  • Editors
  • Git
  • GeoServer
  • GIS
  • H5
  • Jquery
  • Java安卓
  • Json
  • Javascript
  • Leaflet
  • Linux
  • Life-Info
  • Mock
  • MongoDB
  • Network
  • NodeJS
  • NPM
  • React
  • 设计运营
  • SEO
  • SVG
  • TypeScript
  • Tools
  • umi
  • uni-APP
  • Vant
  • Vue
  • Windows
  • webpack
  • 位置:OC中文网 > 其他 > ElementUI >

    element-UI上传组件限制上传文件类型和文件大小

    来源:openlayers-cesium.com 时间:12-15

    element-UI 使用Upload组件上传文件,我们有时候需要设定类型和文件的最大值。如何来操作呢?zjcopy来说明一下

    1. <el-upload 
    2.            :action="actions" 
    3.            accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF" 
    4.            :on-exceed="onExceed" 
    5.            :on-success="onSuccess" 
    6.            :before-upload="beforeUpload" 
    7.             > 
    8.  <el-button slot="trigger" size="small" >选取文件</el-button> 
    9. </el-upload> 

    这里可以看到accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF" ,他的目的是选文件的时候,会把这些类型显示出来。你还是可以选择全部文件,然后上传别的类型的文件。这就说明,accept控制不了我们上传文件的类型。 如何解决呢?

    上传之前:before-upload="beforeUpload"再次判断文件类型

    1. beforeUpload(file) {                 
    2.                 var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)                
    3.                 const zjcopy1 = testmsg === 'jpg' 
    4.                 const zjcopy2 = testmsg === 'gif' 
    5.                 const isLt10M = file.size / 1024 / 1024 < 10 
    6.                 if(!zjcopy1 && !zjcopy2) { 
    7.                     this.$message({ 
    8.                         message: '上传文件只能是 jpg、gif格式!', 
    9.                         type: 'warning' 
    10.                     }); 
    11.                 } 
    12.                 if(!isLt2M) { 
    13.                     this.$message({ 
    14.                         message: '上传文件大小不能超过 10MB!', 
    15.                         type: 'warning' 
    16.                     }); 
    17.                 } 
    18.                 return zjcopy1 || zjcopy12 && isLt10M 
    19.             }