1.html <ul class="uploadUl"> // 第一li用于回显图片,上传接口图片成功后通过canvas进行绘制回显图片。 第二个li 用于选择文件上传 <li style="display: inline-block" v-for="(src,index) in files"> <img @click="ImageToCanvas(src)" class=‘preview‘ :src="src"> <img class="close" @click="close(index,0)" src="../../../../static/img/closea.png"> // 关闭图层 </li> <li style="display: inline-block" class="roomDiv" @click="chooseImg(0)" v-if="this.files.length<1"> <input type=‘file‘ name="doc" ref="choose" accept="image/*" @change=‘setImagePreview($event,0)‘ hidden/> //hidden,隐藏原始的丑陋的input type=‘file‘ <img class="roomIMG" src="../../../../static/img/roomPaizhao.png"> // 自行配置背景图片 </li> </ul>
ImageToCanvas(image) { // 图片绘制事件,此方法可共用 console.log(image) let canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; canvas.getContext("2d").drawImage(image, 0, 0);//0, 0参数画布上的坐标点,图片将会拷贝到这个地方 return canvas; },
chooseImg(index) { // 上传图片的点击事件,可传参 console.log(index) if(index === 0){ this.$refs.choose.click(); }else if(index === 1){ this.$refs.choose1.click(); }},
// 封装一个方法upIMGAjax
upIMGAjax(fileList,imgIndex){ // 上传图片的路径和id console.log(fileList) const that = this ; let formData = new FormData(); formData.append(‘file‘, fileList) let use = sessionStorage.getItem(‘userName‘) ; formData.append(‘uploadUserId‘, use) this.uploadFileRequest(‘‘,formData).then(res =>{ if(res.data.code === 200){ if(imgIndex === 0){ that.roomImgId = res.data.data.id ; that.roomImgUrl = res.data.data.path ; sessionStorage.setItem("roomImgId", res.data.data.id); console.log(that.roomImgId,‘roomId‘) } else if(imgIndex === 1){ that.IDimgId = res.data.data.id ; that.IDimgUrl = res.data.data.path ; } }else{ that.$Toast(res.data.message); } }).catch(res => { // console.log(res) })},
// 图片绘制 (关键函数)
setImagePreview(event,index) { // 图片的绘制 const that = this ; if(index === 0){ this.file.push(event.target.files[0]) // e.target.files[0] 目标文件,固定files不能变名字。 this.files.push(window.URL.createObjectURL(event.target.files[0])) let filess = event.target.files || event.dataTransfer.files if (this.files.length === 0) return; this.createImage(filess, event); this.upIMGAjax(event.target.files[0],0) }else if(index === 1){ this.file1.push(event.target.files[0]) this.files1.push(window.URL.createObjectURL(event.target.files[0])) let filess = event.target.files || event.dataTransfer.files if (this.files1.length === 0) return; this.createImage(filess, event) this.upIMGAjax(event.target.files[0],1) }}, // 上传之前的图片的压缩插件lrz
createImage(file, event) { // 图片的压缩 let _this = this this.lrz(file[0], { width: 100, quality: .5 }).then(function (rst) { _this.file.push(rst.base64) return rst; }).always(function () { event.target.value = null; })},
// 关闭图层
close(val,index) { // 上传图片的关闭事件 if(index === 0){ this.files.splice(val, 1); }else if(index === 1){ this.files1.splice(val, 1); }},
展示效果:
原文地址:https://www.cnblogs.com/panax/p/10960474.html
时间: 2024-10-13 11:19:33