elementui upload
使用 Element UI Upload 组件
Element UI 提供了 el-upload 组件,用于实现文件上传功能。支持多种上传方式,如拖拽上传、手动上传、多文件上传等。
基本用法
通过 action 属性设置上传的接口地址,on-success 和 on-error 分别处理上传成功和失败的回调。
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
:on-success="handleSuccess"
:on-error="handleError">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
methods: {
handleSuccess(response, file, fileList) {
console.log('上传成功', response);
},
handleError(err, file, fileList) {
console.error('上传失败', err);
}
}
拖拽上传
设置 drag 属性可以启用拖拽上传功能。
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
drag
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
限制文件类型和大小
通过 accept 属性限制上传文件的类型,before-upload 钩子可以在上传前对文件进行校验。
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
:before-upload="beforeUpload"
accept=".jpg,.png,.jpeg">
<el-button size="small" type="primary">点击上传图片</el-button>
</el-upload>
methods: {
beforeUpload(file) {
const isImage = file.type.includes('image/');
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isImage) {
this.$message.error('只能上传图片格式文件!');
}
if (!isLt2M) {
this.$message.error('文件大小不能超过 2MB!');
}
return isImage && isLt2M;
}
}
自定义上传行为
通过 http-request 属性可以覆盖默认的上传行为,实现自定义上传逻辑。
<el-upload
:http-request="customUpload">
<el-button size="small" type="primary">自定义上传</el-button>
</el-upload>
methods: {
customUpload(file) {
const formData = new FormData();
formData.append('file', file.file);
axios.post('your-upload-url', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
}).then(response => {
console.log('上传成功', response);
}).catch(error => {
console.error('上传失败', error);
});
}
}
显示上传列表
设置 show-file-list 为 true 可以显示上传的文件列表,通过 on-remove 处理文件移除事件。
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
:on-remove="handleRemove"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
data() {
return {
fileList: []
};
},
methods: {
handleRemove(file, fileList) {
console.log('移除文件', file);
}
}
多文件上传
设置 multiple 属性可以支持多文件上传。
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
multiple>
<el-button size="small" type="primary">点击上传多个文件</el-button>
</el-upload>
常见问题
上传文件时携带额外参数
通过 data 属性可以传递额外的参数到上传接口。
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
:data="{ userId: 123 }">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
跨域问题
如果上传接口存在跨域问题,需确保后端支持 CORS 或配置代理。
文件大小限制
通过 before-upload 钩子可以限制文件大小,避免上传过大的文件。
beforeUpload(file) {
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isLt5M) {
this.$message.error('文件大小不能超过 5MB!');
}
return isLt5M;
}






