效果圖

上傳圖片.jpg
html
<div class="img-box g-f-l" >
<input type="file" class="file-input" @change="addImg()" ref="inputer" accept="image/png">
<div v-if="preview">
<img :src="preview" class="avatar" ref="proPic" id="pro-pic">
</div>
<div v-else style="text-align: center;margin-top: 15px;">
<p>+</p>
<p class="g-c-eff g-fz-12 g-mt-10">上傳logo</p>
</div>
<a class="deleteIcon" @click="deleteImg" v-if="preview"><img src="../assets/close.png" alt=""></a>
</div>
js
data() {
return {
addedPreviewFile:'',
}
},
computed: {
preview() {
return this.addedPreviewFile
},
accept() {
return 'png'
}
},
methods: {
deleteImg() {
this.addedPreviewFile = ''
},
addImg() {
let inputDOM = this.$refs.inputer
let file = inputDOM.files[0]
if (!file) return
let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase();
let fileSize = file.size;
let isImage = false;
for (let mimeType of this.accept.split(',')) {
if (mimeType === testmsg) {
isImage = true;
break
}
}
if (!isImage) {
this.$message.error('上傳圖片必須是PNG格式!');
return false;
}
if (fileSize > 1024 * 1024) {
this.$message.error('上傳圖片大小不能超過1MB!');
return false;
}
let re = new FileReader()
re.readAsDataURL(file)
let that = this
re.onload = function (re) {
that.addedPreviewFile = re.target.result
}
},
}
css
.g-c-eff{color: #409eff;}
.img-box{
width: 82px;
height: 82px;
background-color: #fcfeff;
border:dashed 1px #409eff;
margin-right: 20px;
position: relative;
}
.file-input{
width: 80px;
height: 80px;
position: absolute;
top: 0;
left: 0;
opacity: 0;
cursor: pointer;
}
#pro-pic{
max-width: 80px;
height: 80px;
display: block;
object-fit: scale-down;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.deleteIcon {
position: absolute;
top: -13px;
right: -11px;
display: block;
background-color: #000000;
opacity: 0.8;
text-align: center;
width: 24px;
height: 24px;
line-height: 24px;
border-radius: 50%;
cursor: pointer;
}