废话不多说 先看效果
代码如下:
<template>
<div>
<div>
<el-upload
class="avatar-uploader"
:action="upUrl"
:on-success="handleAvatarSuccess"
list-type="picture-card"
:before-upload="beforeAvatarUpload"
:on-preview="handlePictureCardPreview"
:class="{ disabled: isMax }"
:on-change="change"
:on-remove="remove"
:on-error="error"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</div>
</div>
</template>
<script>
export default {
data() {
return {
upUrl: "http://xxxxxxx:8097/admin/oss/upload/image", //上传地址 必填 (process.env.VUE_APP_BASE_API + '/oss/upload/image')
isMax: false,
dialogImageUrl: "",
dialogVisible: false,
};
},
created() {},
mounted() {},
methods: {
//文件上传成功时的钩子
handleAvatarSuccess(res, file) {
console.log("文件上传成功", res.data);
},
//上传文件之前的钩子,参数为上传的文件,可用作文件大小类型的判断,若返回 false 或者返回 Promise 且被 reject,则停止上传。 function(file)
beforeAvatarUpload(file) {
console.log("文件", file);
// 判断图片格式
const isType =
file.type === "image/png" ||
file.type === "image/jpg" ||
file.type === "image/jpeg" ||
file.type === "image/gif";
// 判断上传图片大小
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isType) {
this.$message.error("上传图标只能为 jpg、png、gif、jpeg格式!!");
return false;
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
return false;
}
return isType && isLt2M;
},
//文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 function(file, fileList)
change(file, fileList) {
console.log("文件改变change");
if (fileList.length >= 3) {
this.isMax = true;
}
},
//文件列表移除文件时的钩子 function(file, fileList)
remove(file, fileList) {
console.log("remove");
if (fileList.length < 3) {
this.isMax = false;
}
},
//上传失败的时候钩子函数 会出现Bug,故在上传失败的时候也进行一下判断 function(err, file, fileList)
error(err, file, fileList) {
this.$message.error("上传失败");
if (fileList.length >= 3) {
this.isMax = true;
} else {
this.isMax = false;
}
},
// 点击文件列表中已上传的文件时的钩子 function(file)
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
},
};
</script>
<style scoped>
::v-deep .avatar-uploader .el-upload {
border: 1px dashed #5d5656;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
::v-deep .avatar {
width: 178px;
height: 178px;
display: block;
}
::v-deep .disabled .el-upload--picture-card {
display: none;
}
</style>