赞
踩
<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>
在上面的代码中,我们使用 Element UI 的 el-upload
组件,该组件实现了将文件上传到服务器的功能。
在组件中定义了一个数据属性 fileList
,用于保存已上传的文件列表。使用 before-upload
钩子函数对即将上传的文件进行验证,只有文件类型为 image/jpeg
或 image/png
且文件大小小于 2MB 时才允许上传。
在 el-upload
组件上绑定了 action
、limit
和 file-list
属性。action
指定了文件上传的URL地址,limit
指定了最多只能上传 1 个文件,file-list
则用于显示已上传的文件列表。
在组件方法中,我们定义了 handleSuccess
方法,在文件上传成功时被调用,清空已上传的文件并打印上传结果。
在 Vue.js 组件的 script
部分中引入 Element UI 的上传组件和 axios
库,并定义了组件名字、数据和方法。
请注意,上面的代码仅供参考,你需要根据自己的具体情况来修改和扩展这个示例。例如,你需要将上传的图片数据传给后端,或者你需要为上传的图片添加一些其他的元数据等。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。