el-upload单个 代码上传文件
时间: 2025-01-13 20:46:13 浏览: 67
### 使用 `el-upload` 实现单个文件上传
为了确保仅允许上传一个文件,在配置 `el-upload` 组件时可以利用其属性来控制这一行为。具体来说,通过设定 `limit="1"` 属性能够有效地限制用户只能选择并上传单一文件[^1]。
下面是一个具体的代码实例展示如何实现这一点:
```html
<template>
<div class="upload-demo">
<!-- 设置 limit=1 来限定只可上传一个文件 -->
<el-upload
action="/api/upload"
:on-preview="handlePreview"
:before-upload="beforeUpload"
:file-list="fileList"
:limit="1"
list-type="text">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传一个文件</div>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
fileList: []
};
},
methods: {
handlePreview(file) {
console.log('preview file:', file);
},
beforeUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 2MB!');
}
// 如果已经有文件存在则不允许再次上传新的文件
if (this.fileList.length > 0 && !this.fileList.includes(file)) {
this.$message.warning('已经有一个文件被选中');
return false; // 阻止上传操作
} else {
return isLt2M;
}
}
}
};
</script>
```
此段代码展示了怎样使用 Vue.js 和 Element UI 的 `el-upload` 组件创建一个简单的界面用于单个文件的选择与上传功能。这里不仅设置了最大上传数目的上限(`limit`),还在 `before-upload` 函数里加入了额外逻辑防止重复添加新文件到列表中去。
阅读全文
相关推荐


















