温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用vue如何实现一个将图片压缩并上传功能

发布时间:2020-11-19 15:29:54 来源:亿速云 阅读:498 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关利用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("http://api139.ys11.ipfsico.com/index/index/realname",data,config).then((res)=>{

      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(/:(.*&#63;);/)[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如何实现一个将图片压缩并上传功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI