ElementUI 提供了一个 el-upload 组件,可以很方便地实现文件上传功能。

首先需要安装 ElementUI:

npm install element-ui --save

然后在需要使用上传组件的页面中引入:

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

<script>
import { ElUpload, ElButton } from 'element-ui';

export default {
  components: {
    ElUpload,
    ElButton
  },
  data() {
    return {
      fileList: []
    };
  },
  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/PNG 格式!');
      }
      if (!isLt500k) {
        this.$message.error('上传图片大小不能超过 500KB!');
      }

      return isJPG && isLt500k;
    },
    onSuccess(response, file, fileList) {
      this.fileList = fileList;
      this.$message.success('上传成功!');
    },
    onError(error, file, fileList) {
      this.$message.error('上传失败!');
    }
  }
};
</script>

以上代码中,el-upload 组件的各个属性和方法的含义如下:

  • action:上传的接口地址。
  • before-upload:上传前的回调函数,参数是上传的文件,返回 false 或者 Promise.reject() 可以阻止上传,返回 true 或者 Promise.resolve() 可以继续上传。
  • on-success:上传成功的回调函数,参数是服务器返回的数据、上传的文件和已上传的文件列表。
  • on-error:上传失败的回调函数,参数是错误对象、上传的文件和已上传的文件列表。
  • auto-upload:是否自动上传,默认为 true。
  • file-list:已上传的文件列表。

在 beforeUpload 回调函数中,我们可以根据文件类型和大小进行限制,返回 false 或者 Promise.reject() 可以阻止上传,返回 true 或者 Promise.resolve() 可以继续上传。

在 onSuccess 回调函数中,我们可以更新已上传的文件列表,以便用户查看已上传的文件。在 onError 回调函数中,我们可以提示用户上传失败的原因。

ElementUI 文件上传组件使用教程 - 实现图片上传功能

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

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