el-upload 上传文件
时间: 2023-09-06 15:14:29 浏览: 120
你可以使用 `el-upload` 组件来实现文件上传功能。`el-upload` 是一个基于 Element-UI 的组件,可以方便地实现文件上传和文件预览的功能。
首先,确保你已经安装了 Element-UI。然后,在你的项目中引入 `el-upload` 组件,并按照以下步骤配置:
1. 在需要使用上传组件的页面中,添加 `el-upload` 标签。例如:
```html
<template>
<div>
<el-upload
class="upload-demo"
action="/your-upload-url"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:limit="3"
:on-exceed="handleExceed"
:auto-upload="false"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
</template>
```
2. 在 `el-upload` 的属性中配置上传相关的参数,例如:
- `action`:设置上传文件的接口地址。
- `on-success`:设置上传成功后的回调函数。
- `before-upload`:设置上传前的钩子函数,用于对文件进行校验或其他操作。
- `limit`:设置最大允许上传的文件数量。
- `on-exceed`:设置超出限制时的回调函数。
- `auto-upload`:设置是否自动上传文件。
3. 在组件的 `methods` 中定义相关函数,例如:
```javascript
methods: {
handleSuccess(response, file, fileList) {
// 上传成功后的处理逻辑
console.log(response, file, fileList);
},
beforeUpload(file) {
// 文件上传前的校验逻辑
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('只能上传 JPG/PNG 格式的图片');
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB');
}
return isJPG && isLt2M;
},
handleExceed(files, fileList) {
// 超出文件数量限制时的处理逻辑
this.$message.warning(`当前限制选择 ${this.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${fileList.length + files.length} 个文件`);
}
}
```
以上是一个简单的 `el-upload` 组件的配置示例。你可以根据自己的需求进行修改和扩展。希望对你有所帮助!
阅读全文
相关推荐
















