ElementUI 文件上传组件使用教程:快速实现文件上传功能
ElementUI 提供了一个非常方便的文件上传组件,可以轻松实现文件上传功能。
首先,需要在项目中引入 ElementUI 的文件上传组件:
import { Upload } from 'element-ui';
然后,在 Vue 组件中使用 Upload 组件:
<template>
<div>
<el-upload
class='upload-demo'
action='//jsonplaceholder.typicode.com/posts/'
:on-success='handleSuccess'
:on-error='handleError'
:before-upload='beforeUpload'>
<el-button size='small' type='primary'>点击上传</el-button>
<div slot='tip' class='el-upload__tip'>只能上传 jpg/png 文件,且不超过 500kb</div>
</el-upload>
</div>
</template>
<script>
export default {
methods: {
handleSuccess(response, file, fileList) {
console.log(response);
},
handleError(error, file, fileList) {
console.log(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/PNG 格式!');
return false;
}
if (!isLt500K) {
this.$message.error('上传图片大小不能超过 500KB!');
return false;
}
return true;
},
},
};
</script>
在这个示例中,我们使用了一个 el-upload 组件来实现文件上传功能。el-upload 组件的 action 属性指定了上传接口的地址,on-success 和 on-error 属性分别指定了上传成功和上传失败的回调函数。before-upload 属性指定了在上传之前要执行的函数,用来验证上传的文件是否符合要求。
在 handleSuccess 回调函数中,我们可以处理上传成功后的响应数据。在 handleError 回调函数中,我们可以处理上传失败后的错误信息。
在 beforeUpload 函数中,我们可以对上传的文件进行验证,如果不符合要求,可以返回 false 来阻止上传。如果符合要求,可以返回 true 来允许上传。
除了这些基本的功能之外,ElementUI 的文件上传组件还提供了许多其他的配置选项,可以根据实际需求来灵活使用。
原文地址: https://www.cveoy.top/t/topic/lAwN 著作权归作者所有。请勿转载和采集!