Element UI 文件上传组件实现教程

1. 安装 Element UI

使用 npm 安装 Element UI:

npm install element-ui --save

2. 导入所需组件

在需要使用文件上传的组件中,导入 el-upload 组件:

<template>
  <div>
    <el-upload
      class='upload-demo'
      action='/upload'
      :on-success='handleSuccess'
      :before-upload='beforeUpload'
      :file-list='fileList'
      :auto-upload='false'>
      <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
      <el-button size='small' type='success' @click='submitUpload'>上传到服务器</el-button>
      <div slot='tip' class='el-upload__tip'>只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        fileList: []
      }
    },
    methods: {
      handleSuccess(response, file, fileList) {
        console.log(response, file, fileList);
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      submitUpload() {
        this.$refs.upload.submit();
      }
    }
  }
</script>

<style>
  .upload-demo {
    display: inline-block;
    margin-bottom: 20px;
  }
</style>

3. 配置参数

el-upload 组件有多个可配置参数,以下是常用参数:

  • action:上传的地址
  • on-success:上传成功的回调函数
  • before-upload:上传前的回调函数
  • file-list:已上传文件列表
  • auto-upload:是否自动上传

4. 运行程序

在 Vue 组件中使用上述代码实现文件上传功能,然后运行程序即可。

以上就是使用 Element UI 实现文件上传的步骤。

Element UI 文件上传组件实现教程

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

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