element上传组件Upload的使用

2,173 阅读1分钟

element上传组件Upload的使用

1、html部分

<el-form ref="ruleForm_1" :model="ruleForm_1" :rules="rules" label-width="120px" class="ruleForm_1">
    <el-form-item label="图片" prop="attachments">
        <el-upload
          class="upload-demo"
          :action="actionUrl"
          :data="{type:'image'}"
          :on-success="handleSuccess"
          :before-upload="handleBeforeUpload"
          :on-remove="handleRemove"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          accept=".jpg,.png,.jpeg"
        >
    </el-form-item>
</el-form>
1.1、属性解析

action: 必选参数,上传的地址
data: 上传时附带的额外参数
on-success:上传成功事件,可以放在这里处理接口所需参数 before-upload:上传前事件,可以在这里做校
on-remove:删除事件
limit:可上传数限制 on-exceed:文件超出个数限制时的钩子
file-list:上传文件的列表
accept:过滤对应格式文件,如上传图片,则在窗口里只会出现文件夹和图片类文件

  • 当然还有一些常用其他的属性没用到(更多可以去el官网)。如:

show-file-list:是否显示已上传文件列表,boolean类型
headers:设置上传的请求头部,如果需要携带token则会用到
list-type:文件列表的类型,默认值是text,可选值有text/picture/picture-card.如下图

  • 默认值:text image.png
  • picture image.png
  • picture-card image.png

2、js部分

export default {
    data() {
        return {
            actionUrl: process.env.VUE_APP_BASE_API + '/file/upload', // 上传组件action地址
            fileList: [], // 用于数据绑定
            ruleForm_1: { // 用于数据请求
                attachments: []
            }
        }
    },
    methods: {
      // 删除上传的图片
      handleRemove(file, fileList) {
          const index = this.fileList.findIndex(item => item.uid === file.uid)
          this.fileList = fileList
          this.ruleForm_1.attachments.splice(index, 1)
      },
      // 上传成功事件(用于数据请求)
      handleSuccess(res, file, fileList) { // 上传成功事件
          this.ruleForm_1.attachments.push({
            name: res.data.name,
            url: res.data.netResourcePath,
            path: res.data.path,
            size: res.data.size
          })
     },
     // 图片超出个数限制时的钩子
     handleExceed(files, fileList) {
         this.$message.warning(`最多只能上传 1 张图片`)
     },
     // 上传图片前事件,校验
     handleBeforeUpload(file) {
         const imgReg = /\.(jpg|png|jpeg)$/
         const isLt1M = file.size / 1024 / 1024 < 2
         if (!imgReg.test(file.name)) {
             this.$message.error('上传图片只能是jpg/png/jpeg格式!')
         }
         if (!isLt1M) {
             this.$message.error('上传图片文件大小不能超过 2MB!')
         }
         return imgReg.test(file.name) && isLt1M
    },
     
   }
}