SoFunction
Updated on 2025-03-03

angularjs client implements compressing image files and uploading instances

It mainly uses html5's canvas to compress the image, then convert it into a dataURL, and then convert the dataURL into a Blob file. The Blob object can be directly assigned to Formdata.

('Util', function($q) {
  var dataURItoBlob = function(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if ((',')[0].indexOf('base64') >= 0)
      byteString = atob((',')[1]);
    else
      byteString = unescape((',')[1]);

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

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

    return new Blob([ia], {
      type: mimeString
    });
  };

  var resizeFile = function(file) {
    var deferred = $();
    var img = ("img");
    try {
      var reader = new FileReader();
       = function(e) {
         = ;

        //resize the image using canvas
        var canvas = ("canvas");
        var ctx = ("2d");
        (img, 0, 0);
        var MAX_WIDTH = 800;
        var MAX_HEIGHT = 800;
        var width = ;
        var 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;
          }
        }
         = width;
         = height;
        var ctx = ("2d");
        (img, 0, 0, width, height);

        //change the dataUrl to blob data for uploading to server
        var dataURL = ('image/jpeg');
        var blob = dataURItoBlob(dataURL);

        (blob);
      };
      (file);
    } catch (e) {
      (e);
    }
    return ;

  };
  return {
    resizeFile: resizeFile
  };

});


Since angualrjs does not currently support uploading files through multiform data, you can use the following code to upload files in formdata

('CompanyCtrl', function($http, Util) {

    ([0]).then(function(blob_data) {
      var fd = new FormData();
      ("imageFile", blob_data);
      $('/upload', fd, {
        headers: {'Content-Type': undefined },
        transformRequest: 
      })
        .success(function(data) {
          $.company_pict = data[0];
        })
        .error(function() {
          ("uploaded error...")
        });
    }, function(err_reason) {
      (err_reason);
    });


}