欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angularjs客户端实现压缩图片文件并上传实例

程序员文章站 2022-03-08 20:28:57
主要是利用html5的canvas来进行图片的压缩,然后转化为dataurl,再有dataurl转化为blob文件,blob对象可以直接赋值给formdata....

主要是利用html5的canvas来进行图片的压缩,然后转化为dataurl,再有dataurl转化为blob文件,blob对象可以直接赋值给formdata.

app.service('util', function($q) {
  var datauritoblob = function(datauri) {
    // convert base64/urlencoded data component to raw binary data held in a string
    var bytestring;
    if (datauri.split(',')[0].indexof('base64') >= 0)
      bytestring = atob(datauri.split(',')[1]);
    else
      bytestring = unescape(datauri.split(',')[1]);

    // separate out the mime component
    var mimestring = datauri.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new uint8array(bytestring.length);
    for (var i = 0; i < bytestring.length; i++) {
      ia[i] = bytestring.charcodeat(i);
    }

    return new blob([ia], {
      type: mimestring
    });
  };

  var resizefile = function(file) {
    var deferred = $q.defer();
    var img = document.createelement("img");
    try {
      var reader = new filereader();
      reader.onload = function(e) {
        img.src = e.target.result;

        //resize the image using canvas
        var canvas = document.createelement("canvas");
        var ctx = canvas.getcontext("2d");
        ctx.drawimage(img, 0, 0);
        var max_width = 800;
        var max_height = 800;
        var width = img.width;
        var height = img.height;
        if (width > height) {
          if (width > max_width) {
            height *= max_width / width;
            width = max_width;
          }
        } else {
          if (height > max_height) {
            width *= max_height / height;
            height = max_height;
          }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getcontext("2d");
        ctx.drawimage(img, 0, 0, width, height);

        //change the dataurl to blob data for uploading to server
        var dataurl = canvas.todataurl('image/jpeg');
        var blob = datauritoblob(dataurl);

        deferred.resolve(blob);
      };
      reader.readasdataurl(file);
    } catch (e) {
      deferred.resolve(e);
    }
    return deferred.promise;

  };
  return {
    resizefile: resizefile
  };

});


由于目前angualrjs暂不支持通过multiform data上传文件,所以利用如下的代码可以上传formdata里的文件

app.controller('companyctrl', function($http, util) {

    util.resizefile(input.files[0]).then(function(blob_data) {
      var fd = new formdata();
      fd.append("imagefile", blob_data);
      $http.post('http://your.domain.com/upload', fd, {
        headers: {'content-type': undefined },
        transformrequest: angular.identity
      })
        .success(function(data) {
          $scope.model.company_pict = data[0];
        })
        .error(function() {
          console.log("uploaded error...")
        });
    }, function(err_reason) {
      console.log(err_reason);
    });


}