利用vue如何实现一个将图片压缩并上传功能-创新互联

今天就跟大家聊聊有关利用vue如何实现一个将图片压缩并上传功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

十年专注成都网站制作,成都定制网页设计,个人网站制作服务,为大家分享网站制作知识、方案,网站设计流程、步骤,成功服务上千家企业。为您提供网站建设,网站制作,网页设计及定制高端网站建设服务,专注于成都定制网页设计,高端网页制作,对白乌鱼等多个方面,拥有丰富的网站设计经验。

上传到服务器的图片太大会导致服务器承受不了,故在前端传图片的时候将图片压缩后再传到服务器


直接上代码

async getRealName(){

    let nickname = this.nickname.trim()

    let idnum = this.idnum.trim()

    let nameReg = /[\u4e00-\u9fa5]/gm

    let idnumReg = /^[a-z0-9]+$/i

    let zheng1 = document.getElementById("file1").files[0]

    let fan1 = document.getElementById("file2").files[0]

    if(nickname.length < 1) {

     return Toast('请输入姓名')

    }

    if(idnum.length < 1) {

     return Toast('请输入身份证号码')

    }

    if(!zheng1) {

     return Toast('请上传身份证信息页')

    }

    if(!fan1) {

     return Toast('请上传身份证国徽页')

    }

    if(zheng1.size/1024 > 1025) {

     this.imgCompress(zheng1,{quality:0.2},'zheng')

    }else {

     this.zheng = zheng1

    }

    if(fan1.size / 1024 > 1025) {

     this.imgCompress(fan1,{quality:0.2},'fan')



    }else {

     this.fan = fan1

    }

 

    setTimeout(()=>{

     let data = new FormData()

     data.append('nickname',nickname);//添加form表单中其他数据

     data.append('idnum',idnum)

     data.append('zheng',this.zheng,zheng1.name)

     data.append("fan",this.fan,fan1.name)

     let apiauth = localStorage.getItem('apiauth')

     let config = {

      headers:{'Content-Type':'multipart/form-data'},

      herders:{apiauth:apiauth}

     }

     axios.post("/tupian/20230522/domain_profile.cfm

      Toast(res.data.msg)

      if(res.data.code == 1) {

       this.$router.replace({path:'/msite'})

      }

     })

    },1000)

 

 

   },

   //图片压缩

   imgCompress(path,obj,statu){

    let _this = this //这里的this 是把vue的实例对象指向改变为_this

    var img = new Image();

    if(statu == 'zheng') {

     img.src = _this.avatar1;

    }else {

     img.src = _this.avatar2

    }

    img.onload = function(){

     var that = this; //这里的this 是把img的对象指向改变为that 

     // 默认按比例压缩

     var w = that.width,

      h = that.height,

      scale = w / h;

     w = obj.width || w;

     h = obj.height || (w / scale);

     var quality = 0.7; // 默认图片质量为0.7

     //生成canvas

     var canvas = document.createElement('canvas');

     var ctx = canvas.getContext('2d');

     // 创建属性节点

     var anw = document.createAttribute("width");

     anw.nodeValue = w;

     var anh = document.createAttribute("height");

     anh.nodeValue = h;

     canvas.setAttributeNode(anw);

     canvas.setAttributeNode(anh);

     ctx.drawImage(that, 0, 0, w, h);

     // 图像质量

     if(obj.quality && obj.quality <= 1 && obj.quality > 0){

      quality = obj.quality;

     }

     // quality值越小,所绘制出的图像越模糊

     var base64 = canvas.toDataURL('image/jpeg', quality);

     // 回调函数返回base64的值

     var urlFile = _this.convertBase64UrlToBlob(base64) //这个地方的处理是为了把压缩的base64转化为对象,获得压缩后图片的大小size,方便对压缩后的图片再次进行判断;

     // console.log(urlFile)

     let file = _this.blobToFile(urlFile,path.name)

     console.log(file)

     if(statu == 'zheng') {

      _this.zheng = file

     }else {

      _this.fan = file

     }

 

     if(urlFile.size/1024 > 1025){

      Toast("图片过大,请重新上传图片")

     }

 

    }

 

   },

   convertBase64UrlToBlob(urlData){

    var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],

     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);

    while(n--){

     u8arr[n] = bstr.charCodeAt(n);

    }

    return new Blob([u8arr], {type:mime});

   },

   blobToFile(theBlob, fileName){

 

    theBlob.lastModifiedDate = new Date();

    theBlob.name = fileName;

    return theBlob;

   },

   changeImage(e) {

    console.log(e.target.files)

    if(e.target.files[0]){

     this.ownImg = false

     var file = e.target.files[0];

     console.log(file)

     let filemaxsize = 4096

     let size = file.size / 1024

     if (size > filemaxsize){

      Toast('您上传的图片过大,请重新选择')

      this.disabled = true;

      this.formatImg = false

      return false

     }

     var name = file.name

     var fileTypes = [".jpg", ".png"];

     if(name) {

      var isNext = false;

      var fileEnd = name.substring(name.indexOf("."));

      for (var i = 0; i < fileTypes.length; i++) {

       if (fileTypes[i] == fileEnd) {

        console.log(fileTypes[i])

        isNext = true;

        this.disabled = false;

        this.formatImg = true;

        break;

       }

      }

      if (!isNext){

       Toast('暂不支持该类型图片');

       name = "";

       this.disabled = true;

       this.formatImg = false

       return false;

      }

     }

     var reader = new FileReader()

     var that = this

     var image = new Image()

     reader.readAsDataURL(file)

     reader.onload = function(e) {

      that.avatar1 = this.result

     }

    }

   },

   changeImg(event){

    var file = event.target.files[0]

    var name = file.name

    var fileTypes = [".jpg", ".png"];

    if(name) {

     var isNext = false;

     var fileEnd = name.substring(name.indexOf("."));

     for (var i = 0; i < fileTypes.length; i++) {

      if (fileTypes[i] == fileEnd) {

       console.log(fileTypes[i])

       isNext = true;

       this.disabled = false;

       this.formatImg = true;

       break;

      }

     }

     if (!isNext){

      Toast('暂不支持该类型图片');

      name = "";

      this.disabled = true;

      this.formatImg = false

      return false;

     }

    }

    var reader = new FileReader()

    var that = this

    reader.readAsDataURL(file)

    reader.onload = function(event) {

     that.avatar2 = this.result

    }

   }

网页名称:利用vue如何实现一个将图片压缩并上传功能-创新互联
文章路径:http://hbruida.cn/article/dgjsic.html