7 字
1 分钟
Vue3使用el-upload上传图片
2025-02-26

Vue#

<el-form-item label="现场照片" prop="urls">
<el-upload
v-model:file-list="imgFileList1"
:action="action"
:headers="imgToken"
:on-success="handleSuccess1"
list-type="picture-card"
:before-upload="beforeAvatarUpload"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove1"
>
<el-icon>
<Plus />
</el-icon>
</el-upload>
</el-form-item>

Data#

//上传图片路径
imgFileList1: [], //图片回显时使用
imgFileListForm: [], //图片回显时使用
piclist1: [], //图片回显时使用
imgToken: {
'Blade-Auth': 'Bearer ' + JSON.parse(localStorage.getItem('saber-token')).content
},
limitImg: 10, //限制图片上传的数量
action: `/api/blade-resource/oss/endpoint/put-file`,
disabled: false,
dialogImageUrl: '', //如果只是显示一张图片的话,可以直接对其赋值
dialogVisible: false

methods#

beforeAvatarUpload(file) {
const imgType = file.type === 'image/jpeg' || file.type === 'image/png';
const imgSize = file.size / 1024 / 1024 < 5;
if (!imgType) {
this.$utils.toast('图片只能是 JPG/PNG 格式!', 'error');
}
if (!imgSize) {
this.$utils.toast('图片大小不能超过 5MB!', 'error');
}
return imgType && imgSize;
},
handlePictureCardPreview(uploadFile) {
this.dialogImageUrl = uploadFile.url;
this.dialogVisible = true;
},
handleRemove1(res) {
console.log(res);
let index = this.imgFileListForm.findIndex(e => e === res.url);
this.imgFileListForm.splice(index, 1);
console.log(this.imgFileListForm);
},
handleSuccess1(res) {
if (res.code === 200) {
this.imgFileListForm.push(res.data.link);
}
},

图片回显#

//在查询到数据的地方
if (this.form.images) {
this.form.images.forEach(value => {
this.imgFileList1.push({ url: value });
});
}
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

Vue3使用el-upload上传图片
https://blog.olinl.com/posts/vue-el-upload/
作者
顾拾柒
发布于
2025-02-26
许可协议
CC BY-NC-SA 4.0

目录