Uploding File using Base-64 in angularJs

We’ll learn how to convert an image/pdf to base 64 in angular js by creating a directive and adding extra parameters for the base 64 data

Creating a input of type file in html:

<input type="file" id="fileSelector1" class="form-control" name="schemeupload" accept="image/jpeg,image/png,application/pdf" file-model="vm.schemeApply.documents[0]" required/>

To accept only image of type jpeg we can use the following in html accept

accept="image/jpeg"

To accept multiple documents say image files and pdf we can use the accept as

    accept="image/jpeg,image/png,application/pdf"

We will create a directive named file-model to convert the file into base64

  "use strict";
(function() {
angular.module("SS.pages").directive("fileModel", fileModel);

 /** @ngInject */
 function fileModel($parse, $q) {
return {
  restrict: "A",
  link: function(scope, element, attrs) {
    var model = $parse(attrs.fileModel),
      modelSetter = model.assign;
    element.bind("change", function() {
      scope.$apply(function() {
        var file = element[0].files[0];
        getFileBuffer(file).then(function(resp) {
          modelSetter(scope, resp);
        });
      });
    });
  }
};
function getFileBuffer(file) {
  var deferred = new $q.defer();
  var reader = new FileReader();
  reader.onloadend = function(e) {
    deferred.resolve(e.target.result);
  };
  reader.onerror = function(e) {
    deferred.reject(e.target.error);
  };
  reader.readAsDataURL(file);
  return deferred.promise;
}
 }

})();

In this directive we are getting the file and we are converting the file into a string(base64) using file reader.

To add Extra parameters for the image(which is converted into base64)

vm.schemeApply.documents.map(function(img, i) {
        return {
          name: "Additional Documents: " + (i + 1),
          document_data_url: img,
          ext: base64MimeType(img)
        };
      });

Note: We should not store the base 64 image directly to database since it takes more space as well as the max file size allowed to convert is 24 (MB).

Comments

Popular posts from this blog

Google play Impersonation and Intellectual Property

Creating Gauge chart in React Native

React Native Splash Screen