VUE 实现OSS 上传图片并压缩处理,签名由后端返回。

 
      

更换头像

  这个是util.js

  /** 图片压缩 返回base64 */
  dealImage(path, obj, callback){
      var img = new Image();
      img.src = path;
      img.onload = function(){
          var that = this;
          // 默认按比例压缩
          var w = that.width,
              h = that.height,
              scale = w / h;
          w = obj.width || w;
          h = obj.height || (w / scale);
          var quality = 0.8;  // 默认图片质量为0.9
          //生成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的值
          callback(base64);
      }
  },

  /** base64转file
   * filename图片的名字,dataurl是base64地址
   */
  dataURLtoFile(dataurl, filename) {
      var arr = dataurl.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 File([u8arr], filename, {type:mime});
  }
//选择图片上传
     selectImage(){
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
        var browser = navigator.userAgent.toLowerCase();
        if (isAndroid && browser.indexOf(' qq') != -1 && browser.indexOf('mqqbrowser') != -1) { $("#file").attr('capture','camera');}
        document.getElementById('file').click();
     },

     //图片上传压缩处理
     change(e){
        var that = this;
        let file = e.target.files[0];
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          that.util.dealImage(this.result, {width: 1024,height:1024}, function (base) {
            var filet = that.util.dataURLtoFile(base,file.name);
            that.upload(filet);
          });
        }
     },

     //上传图片
     async upload(file){
        var that = this
        let fileinfo = [];
        fileinfo.push({name:file.name, size:500, filePath:file.tempFilePath});
        const json = await this.http.request(this.api.u('getOssPolicy'),'post',{id:this.id,fileType:'userPortrait',originalFileInfoArr:JSON.stringify(fileinfo)},false);
        if(json.data.returnCode==0){
            var AuthMsg = json.data.result
            var imgExit = file.name.split('.')[1];
            var ossKey  = AuthMsg.dir + AuthMsg.uploadNameList[0] + '.'+imgExit;
            var imgurl  = AuthMsg.host + '/' + ossKey;
            this.$vux.loading.show({text:'上传中...'});
            // 添加签名信息
            var ossData = new FormData();
            ossData.append('OSSAccessKeyId', AuthMsg.accessKeyId);
            ossData.append('policy', AuthMsg.policy);
            ossData.append('Signature', AuthMsg.postSignature);
            ossData.append('key',ossKey);
            ossData.append('callback', AuthMsg.callback);
            // 添加文件
            ossData.append('file', file, AuthMsg.uploadNameList[0]);
            ossData.append('success_action_status', 200);
            $.ajax({
                url: AuthMsg.host,
                data: ossData,
                processData: false,
                contentType: false,
                type:'POST',
                success:function (data) {
                   that.headimg = that.util.thumbImg(imgurl,'h3');
                   that.form.portrait = imgurl;
                   that.$vux.loading.hide();
                },
                error:function(err){
                   that.$vux.toast.text(err);
                   that.$vux.loading.hide();
                }
            })
        }else{
          this.$refs.login.checkLogin(json.data);
        }
     },

 

你可能感兴趣的:(JQUERY,+,JS,+,CSS,VUE)