Skip to main content

Command Palette

Search for a command to run...

Converting a File to Base64 in angularJs

Updated
2 min read

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

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

To accept the 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 images directly to the database since it takes more space, as well as the max file size allowed to convert, is 24 (MB).

More from this blog

Nidhin's blog

168 posts

✨Crafting Code with a Smile for 8 Years:) Merging the Formal Dance of Angular, the Playful Rhythms of React, and the Next-level Moves of Next.js 🚀