一、html代码:
<el-upload :show-file-list="false" :http-request="uploadFile"
list-type="picture-card" :limit="1" accept=".png" class="el-upload" :before-upload="beforeAvatarUpload">
<div class="el-upload--picture-card">
<img v-if="path" :src="(host || '') + avatar" class="avatar card" />
<i v-else class="el-icon-plus avatar-uploader-icon "></i>
</div>
</el-upload>
<div class="text">
<p>大小不超过10MB</p>
</div>
二、js代码
data数据:
host: null,
avatar: null,
path: null,
avatarLocal: null,
校验图片大小:
beforeAvatarUpload(file) {
// console.log(file, 'file====上传前=');
// file.size < 10 * 1024 * 1024
const isLtM = file.size / 1024 / 1024 < 10;
if (!isLtM) {
this.$message.error("上传头像图片大小不能超过 10MB!");
}
return isLtM
},
上传图片:
uploadFile(params) {
console.log(params, "覆盖上传");
let formdata = new FormData();
const _file = params.file;
formdata.append("file", _file);
UserAPI.GameimageUpload(formdata).then((res) => {
// console.log(res, 'res====');
if (res.data.code === 0) {
this.path = res.data.data.host + res.data.data.path;
this.host = res.data.data.host;
this.avatar = res.data.data.path;
// console.log(this.path, '===', this.host, '===', this.avatar);
const userDataString = localStorage.getItem('user');
const userData = JSON.parse(userDataString);
userData.avatar = this.path;
// localStorage.setItem('user', JSON.stringify(userData));
this.$store.dispatch('user/setUser', {...JSON.parse(localStorage.getItem('user')), avatar: this.path });
// this.$emit('loginUser_')
this.$message.success(res.data.msg);
// this.updateVisible(false);
}
});
},