前端图片的上传压缩(vue)

164 阅读1分钟

html样式为: <input class="hiddenInput" type="file" name="uploadFile" id="imageFile" accept="image/*" @change="uploadImg($event)"/>  methods函数部分为: uploadImg(e){ const file=e.target.files[0]; this.photoCompress(file,(base64Codes)=>{  let form =new FormDate();  form.append("op;loadFile",b1,`file_${Date.parse(new Date())}.jpg`);  UploadImgInClaim(form).then((res)=>{   if(res.status){     let url=window.URL.createObjectURL(file);   }  }).catch((err)=>{    console.log(err);  }) }) }, //图片压缩 photoCompress(file,objDiv){  let reader=new FileReader();  reader.readAsDataURL(file);  reader.onload=function(){    let result=this.result;    this.canvasDataURL(result,file,objDiv);  } }, canvasDataURL(path,file,callback){  let img=new Image();  img.src=path;  img.onload=function(){    let _this=this;    //按比例默认缩放    let w=_this.width;    let h=_this.height;    let quality=0.7;    //生成canvas    let canvas=document.createElement("canvas");    let ctx=canvas.getContext("2d");    //创建属性节点      // 创建属性节点        let anw = document.createAttribute('width')        anw.nodeValue = w        let anh = document.createAttribute('height')        anh.nodeValue = h        canvas.setAttributeNode(anw)        canvas.setAttributeNode(anh)        ctx.drawImage(_this, 0, 0, w, h)           // 图像质量        console.log(`压缩之前的大小:${file.size / 1024}kb`)        if (file.size > 300 * 1024) {          quality = 0.3        }        // quality值越小,所绘制出的图像越模糊        let base64 = canvas.toDataURL('image/jpeg', quality)        callback(base64)  } },  convertBase64UrlToBlob (urlData) {      let arr = urlData.split(',')      let mime = arr[0].match(/:(.*?);/)[1]      let bstr = atob(arr[1])      let n = bstr.length      let u8arr = new Uint8Array(n)      while (n--) {        u8arr[n] = bstr.charCodeAt(n)      }      return new Blob([u8arr], { type: mime })    }