当前位置:   article > 正文

使用 Element UI 将图片上传到后端的 Vue.js 示例:_vue上传图片到后端

vue上传图片到后端

使用 Element UI 将图片上传到后端的 Vue.js 示例:

<template>
  <div>
    <h1>上传图片</h1>
    <el-upload
      class="upload-demo"
      action="/upload"
      :on-success="handleSuccess"
      :limit="1"
      :before-upload="beforeUpload"
      :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过2M</div>
    </el-upload>
  </div>
</template>

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

export default {
  name: 'ImageUploader',
  components: { ElUpload, ElButton },
  data() {
    return {
      fileList: []
    };
  },
  methods: {
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg/png文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过2MB!');
        return false;
      }
      return true;
    },
    async handleSuccess(response) {
      this.fileList = []; // 清空已上传的文件
      this.$message.success('文件上传成功!');
      console.log('上传结果:', response);
    }
  }
};
</script>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

在上面的代码中,我们使用 Element UI 的 el-upload 组件,该组件实现了将文件上传到服务器的功能。

在组件中定义了一个数据属性 fileList,用于保存已上传的文件列表。使用 before-upload 钩子函数对即将上传的文件进行验证,只有文件类型为 image/jpegimage/png 且文件大小小于 2MB 时才允许上传。

el-upload 组件上绑定了 actionlimitfile-list 属性。action 指定了文件上传的URL地址,limit 指定了最多只能上传 1 个文件,file-list 则用于显示已上传的文件列表。

在组件方法中,我们定义了 handleSuccess 方法,在文件上传成功时被调用,清空已上传的文件并打印上传结果。

在 Vue.js 组件的 script 部分中引入 Element UI 的上传组件和 axios 库,并定义了组件名字、数据和方法。

请注意,上面的代码仅供参考,你需要根据自己的具体情况来修改和扩展这个示例。例如,你需要将上传的图片数据传给后端,或者你需要为上传的图片添加一些其他的元数据等。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读