制作效果:
上传图片之前(初始效果):
上传图片之后(使用效果):
制作代码:
// html :
<form class="photoUpload">
<div class="uplloadFlex">
<div v-for="(item,index) in picList" :key="index" class="imgView">
<img :src="'data:image/jpg;base64,'+item.picBase64" alt="" class="showPic" >
<img src="@/assets/image/delete.png" alt="" class="delIcon" @click="delImg(item.no)">
</div>
<div class="uploadView" v-show="picList.length<5">
<input id="uploadBtn" type="file" ref="upload" accept="image/*" class="uploadBtn" @change="handleFileChange" />
<img src="@/assets/image/add.png" alt="" style="width:30px;heigth:30px;">
</div>
</div>
</form>
// data :
export default {
data() {
return {
picList:[]
}
},
}
// metheds:
created() {
this.id = this.$route.params.id; //唯一标识
console.log(this.id);
this.DownloadPicture(this.id)
},
methods: {
// 删除图片
delImg:function(no){
this.$http
.post("/接口名",{no:no})
.then((res) => {
if(res.data._RejCode == '000000'){
this.$message.success('删除成功')
this.picList.splice(this.picList.findIndex(e => e.no === no), 1)
}
})
.catch((err) => {
console.log(err);
});
},
//手动保存图片并限制图片大小
handleFileChange:function(e){
var test = document.getElementById('uploadBtn');
const files = e.target.files;
if(files && files[0]) {
const file = files[0];
if(file.size > 1024 * 1024 *3) {
test.value=''
return false;
} else {
this.getBase64(files[0]).then((res)=>{
test.value=''
this.uploadImg(res)
})
}
}
},
// 下载图片
DownloadPicture:function(id){
this.$http
.post("/接口名",{id:id})
.then((res) => {
if(res.data._RejCode == '000000'){
this.picList = res.data.pictureList
}
console.log(this.picList);
})
.catch((err) => {
console.log(err);
});
},
// 从后端传入图片
uploadImg:function(base64){
var params = {
picBase64:base64.split(',')[1],
id:this.id
}
this.$http
.post("/接口名",params)
.then((res) => {
params.no = res.data.no;
this.picList.push(params)
})
.catch((err) => {
console.log(err);
});
},
// 获取图片转base64格式
getBase64(file) {
return new Promise(function(resolve, reject) {
const reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function() {
imgResult = reader.result; //base64编码
};
reader.onerror = function(error) {
reject(error);
};
reader.onloadend = function() {
resolve(imgResult);
};
});
},