ElementUI 提供了上传组件 el-upload,可以实现文件上传功能。

首先,在组件中引入 el-upload 组件:

<template>
  <el-upload
    class='upload-demo'
    action='/upload'
    :on-success='handleSuccess'
    :on-error='handleError'
    :file-list='fileList'
    :auto-upload='false'>
    <el-button size='small' type='primary'>点击上传</el-button>
    <div slot='tip' class='el-upload__tip'>只能上传jpg/png文件,且不超过500kb</div>
  </el-upload>
</template>

其中,action 属性指定上传地址,on-successon-error 分别为上传成功和失败的回调函数,file-list 属性绑定上传文件列表,auto-upload 属性控制是否自动上传。

接下来,在组件的 methods 中定义 handleSuccesshandleError 方法:

export default {
  data() {
    return {
      fileList: []
    };
  },
  methods: {
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
      this.$message({
        message: '上传成功',
        type: 'success'
      });
    },
    handleError(err, file, fileList) {
      this.fileList = fileList;
      this.$message({
        message: '上传失败',
        type: 'error'
      });
    }
  }
}

其中,handleSuccess 方法在上传成功时触发,将上传成功的文件列表赋值给 fileList 属性,并弹出上传成功的提示信息;handleError 方法在上传失败时触发,同样将上传失败的文件列表赋值给 fileList 属性,并弹出上传失败的提示信息。

最后,还可以通过 before-upload 属性来控制上传文件的类型和大小:

<el-upload
  ...
  :before-upload='beforeUpload'
  ...
>
methods: {
  beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt500K = file.size / 1024 < 500;

    if (!isJPG) {
      this.$message.error('上传头像图片只能是 JPG 格式!');
    }
    if (!isLt500K) {
      this.$message.error('上传头像图片大小不能超过 500KB!');
    }
    return isJPG && isLt500K;
  }
}

beforeUpload 方法中,判断文件类型和文件大小是否符合要求,如果不符合,则弹出对应的提示信息,并返回 false,阻止文件上传。如果符合要求,则返回 true,允许文件上传。

完整的实现代码如下:

<template>
  <el-upload
    class='upload-demo'
    action='/upload'
    :on-success='handleSuccess'
    :on-error='handleError'
    :file-list='fileList'
    :auto-upload='false'
    :before-upload='beforeUpload'>
    <el-button size='small' type='primary'>点击上传</el-button>
    <div slot='tip' class='el-upload__tip'>只能上传jpg/png文件,且不超过500kb</div>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      fileList: []
    };
  },
  methods: {
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
      this.$message({
        message: '上传成功',
        type: 'success'
      });
    },
    handleError(err, file, fileList) {
      this.fileList = fileList;
      this.$message({
        message: '上传失败',
        type: 'error'
      });
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    }
  }
}
</script>
ElementUI 文件上传组件使用指南 - 实现简单高效的上传功能

原文地址: https://www.cveoy.top/t/topic/lAwP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录