el-upload上传 单个图片
时间: 2025-06-05 15:35:54 浏览: 16
### 使用 `el-upload` 组件上传单个图片
为了实现使用 `el-upload` 组件来上传单张图片的功能,可以按照以下方式配置该组件。此方法允许用户选择并上传一张图片到服务器。
#### 基本模板结构
```html
<template>
<div class="upload-demo">
<!-- 设置属性 :limit=1 来限制只可上传一个文件 -->
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:before-upload="beforeAvatarUpload"
:file-list="fileList"
:limit="1"
:on-exceed="handleExceed"
ref="uploadRef">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</div>
</template>
```
#### 脚本部分逻辑
```javascript
<script>
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
fileList: []
};
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
}
}
};
</script>
```
上述代码展示了如何利用 `el-upload` 实现单一图片的选择与上传功能[^1]。这里设置了 `list-type="picture-card"` 属性用于显示缩略图样式;并通过 `:limit="1"` 控制仅能上传一张照片。同时提供了钩子函数如 `before-avatar-upload` 对上传前的文件做校验工作,以及 `handle-picture-card-preview` 和 `handle-remove` 方法分别用来处理预览和移除事件。
阅读全文
相关推荐


















