首先要知道上傳文件以及文件刪改查的前后端約定規范:
增加:傳遞給后端你所選擇的文件流,同時進行圖片的回顯;
編輯:分為兩種情況:
1.你只編輯其余文本信息,對圖片區域不進行任何修改。此時你不需要傳遞任何和圖片相關的參數;
2.對圖片進行了增刪改。增加的圖片就傳遞對應的file流,刪除的圖片傳遞給后端圖片對應id。
刪除:傳遞給后端刪除的圖片id集合(這個id是后端給你的)
<div >
<div v-for='(item ,index ) in imgList' :key="index"
style="width: calc(20% - 7px);margin-right:5px;margin-bottom:5px;border:1px solid #ddd;" :style="{backgroundImage:'url(' + item.img_addr + ')',
backgroundRepeat:'no-repeat',position: 'relative', backgroundPosition:'center center', backgroundSize: 'contain'}">
<span @click='delImg(index,item.image_id)'><img src="@static/images/delete.png"></span>
</div>
<div class='room_add_img' style="width: calc(20% - 5px);margin-right:5px;margin-bottom:5px;"
>
<span><img src="@static/images/add_img.png"></span>
<span>上傳圖片</span>
<input @change='addImg' id="imgUpdateId" type="file">
</div>
</div>
<script>
export default{
data(){
return {
fd:null,//formData,和后端進行數據交互
imgList:[],//圖片的地址結合,通過地址展示到頁面中
oldImageIDs:[],//刪除時,需要向后端傳遞的刪除圖片的id集合
fileArr:[],//文件流集合
}
},
methods:{
addImg(event){
//添加圖片,event是input默認參數,其中里面的files是我們需要的文件流,可以打印一下看看里面的各個參數,了解了解
if(this.imgList){
//限制最多添加五張圖片
if (this.imgList.length >= 5) {
this.$message.warning('最多只能上傳5張圖片!');
return
}
}
var file =
event.target.files[0];//獲取當前的文件流,這就是你傳遞給后端的參數
//校驗圖片的類型和大小
const isJPG = file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/gif';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上傳頭像圖片只能是 JPG/PNG/GIF 格式!');
return;
}
if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過 2MB!');
return;
}
var reader = new FileReader();//
使用FileReader對象,來進行異步文件的讀取,是input:file的絕配
reader.readAsDataURL(file);
var that = this;
reader.onloadend = function (e) {
//這個e是默認形參,里面有圖片的base64轉換結果,以及上傳速度之類的信息。
當然我們一般都需要這個base64的結果,進行上傳圖片的回顯
that.fileArr.push(file);//設置向后端傳遞的參數
that.imgList.push({img_addr: reader.result})//設置回顯圖片的地址(base64格式)
}
},
editOrder(row) {
//row是編輯時表單的數據信息,不在多說
//編輯時,
必須將刪除id集合,以及文件流集合清空,否則后續會出現錯亂問題。
this.oldImageIDs= [];
this.fileArr = [];
row.imgUrl.forEach(item=>{
item.img_addr = window.$url_front.fileUrl+item.image_url;//設置圖片的線上地址,進行回顯
})
this.imgList = row.imgUrl; //賦值圖片列表,每一個對象都會有一個id,
這個id是后端所返,根據此id進行刪除操作
.
.
.
//在此僅進行圖片的操作,表單的其他賦值操作不在描述,
},
delImg(item, imgId) {
//刪除圖片
this.imgList.splice(item, 1);
if (imgId) {
this.oldImageIDs.push(imgId); //設置刪除圖片的id集合,
} else {
this.fileArr.splice(item , 1);
}
document.getElementById('imgUpdateId').value = '';
},
saveItem(){
//保存
}
this.fd = new FormData();
this.fileArr.map(item => {
//設置文件流集合
this.fd.append('files', item)
});
this.fd.append('img_ids',this.oldImages)
//設置所刪除的圖片id集合
api.........//進行數據交互就行了
}
}
</script>
ps:前端和后端進行圖片的交互,其實就是用base64碼進行二進制文件的數據交互。