<template>
<el-form-item label="封面图">
<el-upload
class="avatar-uploader"
action="http://主机:8080/file/upfile"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="defaultCoverImage" :src="defaultCoverImage" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
</template>
<script>
export default {
data(){
return{
defaultCoverImage: "", //业务需求需要多定义一个defaultCoverImage
form: { defaultCoverImage: "", //默认封面图}
},
methods(){
// 封面图上传成功执行的方法
handleAvatarSuccess(res, file) {
//window.uploadImgUrl:文件路劲提取成全局变量
this.defaultCoverImage = window.uploadImgUrl + res.data;
this.form.defaultCoverImage = window.uploadImgUrl + res.data;
},
// 封面图上传之前执行的方法
beforeAvatarUpload(file) {
const isJPG =
file.type === "image/jpeg" ||
file.type === "image/jpg" ||
file.type === "image/png";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error("上传头像图片只能是 JPG PNG JPEG 格式!");
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
}
return isJPG && isLt2M;
}
}
}
}
}
}
</script>
注意不要让后台修改文件的名字,就叫file,否则上传不成功。