图片上传,该文中用到的是Element - The world's most popular Vue UI framework upload组件
具体代码:
<div class="upload-container" style="pointer-event:none" >
<img v-if="formItem.faceImgPath" class="avater" :src="formItem.faceImgPath" />
<el-upload
ref="getFaceImgPath"
v-show="!formItem.faceImgPath"
class="upload-demo"
drag
:show-file-list="false"
:http-request="getFaceImgPath" //上传的实现
action="#"
accept=".jpg,.png"
:before-upload="beforeAvatarUpload"
>
<span style="color:blue">点击上传/</span>
<span>拖拽到此区域</span>
</el-upload>
<div class="info-container" v-if="formItem.faceImgPath">
<div class="btn-wrap">
<span @click="btnUpload()">重新上传</span>
<span style="margin-left:16px;" @click="deleteImg()">删除</span>
</div>
</div>
</div>
<span>请上传JPG、PNG格式图像,尺寸为2.5*3.5cm,大小在200k内</span>
JS实现
// 上传文件前回调 限制图片大小
beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 0.2
if (!isLt2M) {
this.$Message.warning('上传头像图片大小不能超过 200K!');
}
return isLt2M;
},
// 自定义上传的实现
getFaceImgPath(content) {
this.getBase64(content.file).then(res => {
// this.$set() 向对象中添加属性,并且是响应式的
this.$set(this.formItem,'faceImgPath', res)
})
},
// 转城base64文件
getBase64(file) {
return new Promise(function (resolve, reject) {
let reader = new FileReader()
let imgResult = ""
reader.readAsDataURL(file)
reader.onload = function () {
imgResult = reader.result
}
reader.onerror = function (error) {
reject(error)
}
reader.onloadend = function () {
resolve(imgResult)
}
})
},
//重新上传
btnUpload() {
this.$refs.getFaceImgPath.$children[0].$refs.input.click()
},
// 删除按钮
deleteImg(type) {
this.formItem.faceImgPath = "";
},
css部分
.upload-container {
padding: 16px 0 16px 16px;
border: 1px dashed #d6dbe3;
width: 344px;
height: 144px;
display: flex;
justify-content: flex-start;
.avater {
width: 112px;
height: 112px;
}
.upload-demo {
height: 100px;
width: 300px;
text-align: center;
line-height: 100px;
border: none;
cursor: pointer;
}
.upload-demo /deep/ .el-upload-dragger {
height: 100px;
line-height: 100px;
width: 300px;
border: none;
background: transparent;
text-align: center;
line-height: 100px;
}
.info-container {
margin-left: 16px;
.btn-wrap {
position: relative;
bottom: -60px;
color: #1f64df;
font-size: 14px;
display: flex;
justify-content: flex-start;
span {
cursor: pointer;
}
}
}
}
有问题欢迎指出~