页面展示效果
HTML部分代码`
<div class="LeaderBuild_BaseInfo">
<div class="main_left">
<div class="main_left_title">
<div>基本信息</div>
</div>
<div class="main_left_touxiang marginTop" @click="clickUpload">
<span v-if="!showImg">上传照片</span>
<img :src="imageUrl" alt="" v-else ref="imgRef">
<input v-show="false" ref="uploadRef" type="file" @change="uploadFile" />
</div>
<div class="main_left_yaoqiu marginTop">
<div>上传照片要求: </div>
<div class="main_left_yaoqiu_main">
上传照片为免冠证件照,正面二寸 (35mm*45mm),支持JPG、JPEG、gif、PNG格式,大小为2MB以下。
</div>
</div>
</div>
</div>
JS部分
data() {
return {
imageUrl: '',
showImg: false,
}
},
methods: {
// 因为input的样式不是我需要的,我的方法是首先隐藏input,然后点击上传照片调用input的uploadFile事件
clickUpload() {
this.$refs.uploadRef.click();
},
uploadFile(e) {
const file = e.target.files[0];
const reader = new FileReader();
let fileResult = '';
reader.readAsDataURL(file);
reader.onload = (e) => {
fileResult = e.target.result;
this.beforeAvatarUpload(file, fileResult);
}
},
beforeAvatarUpload(file, fileResult) {
const img = new Image();
img.src = fileResult;
img.onload = () => {
if (img.width / img.height !== 413 / 626) {
return this.$message.error('请上传2寸照片');
}
const imgType = ['image/jpeg', 'image/png', 'image/gif', 'image/jpeg'];
if (!imgType.includes(file.type)) {
return this.$message.error('上传头像图片仅支持JPG、JPEG、gif、PNG格式!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
return this.$message.error('上传头像图片大小不能超过 2MB!');
}
// imageUrl 即图片src可以用上传文件的url也可以用base64
// this.imageUrl = URL.createObjectURL(file);
this.imageUrl = fileResult;
this.showImg = true;
}
},
},
CSS部分
.LeaderBuild_BaseInfo {
width: 300px;
}
.main_left {
width: 100%;
height: 100%;
border: 1px solid #f0f5ff;
padding: 4%;
color: #606266;
font-size: 0.16rem;
}
.marginTop{
margin-top: 20px;
}
.main_left_title {
color: #585858;
font-weight: bold;
}
.main_left_touxiang {
width: 120px;
height: 150px;
line-height: 150px;
margin: 0 auto;
margin-top: 16px;
background: #F2F5F9;
color: #596B89;
text-align: center;
cursor: pointer;
}
img {
width: 120px;
height: 150px;
}
.main_left_yaoqiu{
color: #C8CCD4;
font-size: 0.14rem;
}
.main_left_yaoqiu_main{
line-height: 2vh;
text-indent: 20px;
}