vue Base64图片压缩上传OSS

   this.compress(result, 800, 0.5).then(val => {
        //得到压缩图片
        let data = val;
        that.file = that.dataURLtoFile(data, that.file_name);
    //上传
        that.upload();
      });
  // 压缩图片
    compress(base64String, w, quality) {
      // var getMimeType = function(urlData) {
      //   var arr = urlData.split(",");
      //   var mime = arr[0].match(/:(.*?);/)[1];
      //   // return mime.replace("image/", "");
      //   return mime;
      // };
      var newImage = new Image();
      var imgWidth, imgHeight;

      var promise = new Promise(resolve => (newImage.onload = resolve));
      newImage.src = base64String;
      return promise.then(() => {
        imgWidth = newImage.width;
        imgHeight = newImage.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
            canvas.width = w;
            canvas.height = (w * imgHeight) / imgWidth;
          } else {
            canvas.height = w;
            canvas.width = (w * imgWidth) / imgHeight;
          }
        } else {
          canvas.width = imgWidth;
          canvas.height = imgHeight;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        // var base64 = canvas.toDataURL(getMimeType(base64String), quality);
        var base64 = canvas.toDataURL("image/jpeg", quality);
        console.log(base64);
        return base64;
      });
    }
 dataURLtoFile(dataurl, filename) {
      let arr = dataurl.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);
      }
      try {
        return new File([u8arr], filename, { type: mime });
      } catch (err) {
        /**兼容iOS9.3或者Android4.4以下版本*/
        console.warn(
          "Browser does not support the File constructor,Will use blob instead of file"
        );
        return this.dataURL2blob(dataurl);
      }
    },
    /**
     * dataURL 转成 blob
     * @param dataURL
     * @return blob
     */
    dataURL2blob(dataURL) {
      let binaryString = atob(dataURL.split(",")[1]);
      let arrayBuffer = new ArrayBuffer(binaryString.length);
      let intArray = new Uint8Array(arrayBuffer);
      let mime = dataURL.split(",")[0].match(/:(.*?);/)[1];
      for (let i = 0, j = binaryString.length; i < j; i++) {
        intArray[i] = binaryString.charCodeAt(i);
      }
      let data = [intArray];
      let result;
      try {
        result = new Blob(data, { type: mime });
      } catch (error) {
        window.BlobBuilder =
          window.BlobBuilder ||
          window.WebKitBlobBuilder ||
          window.MozBlobBuilder ||
          window.MSBlobBuilder;
        if (error.name === "TypeError" && window.BlobBuilder) {
          var builder = new BlobBuilder();
          builder.append(arrayBuffer);
          result = builder.getBlob(type);
        } else {
          throw new Error("没救了");
        }
      }
      return result;
    },
    async upload() {
      try {
        let that = this;
        let params = { filename: that.file_name };
        console.log(params.filename);
        //获取签名
        Api.barthday2.getsign(params).then(res => {
          if (res.code == 0) {
            that.uploadFile(res.data.Sign);
          } else {
            that.$toast.clear();
            this.$toast(res.message);
          }
        });
      } catch (err) {
        that.$toast.clear();
        that.$toast(err);
      }
    },
    async uploadFile(url) {
      let that = this;
      let config = {
        headers: {
          "Content-Type": "application/octet-stream"
        }
      }; //添加请求头
      this.$http
        .put(url, this.file, config)
        .then(response => {
           //上传oss成功后把图片地址给服务器
          
        })
        .catch(res => {
          that.$toast("抱歉,系统异常,上传失败!");
        });
    },    

 

posted @ 2019-11-07 14:06  说好范特西  阅读(1563)  评论(0编辑  收藏  举报