Get base64 string of a file in ionic

14,922

Solution 1

phonegap-base64. It is cordova plugin and worked for me as well.

Solution 2

Use angular-base64 plugin for that. The link is here: https://github.com/ninjatronic/angular-base64.
It is easy to use. Inject the dependency in module as:

angular
    .module('myApp', ['base64'])
    .controller('myController', ['$base64', '$scope',function($base64, $scope) {

            $scope.encoded = $base64.encode('a string');
            $scope.decoded = $base64.decode('YSBzdHJpbmc=');
    }]);

And,remember to include the reference in index.html.

<script src="bower_components/angular-base64/angular-base64.js"></script>

Solution 3

You could take a look at this:

How to use it:

angular
    .module('myApp', ['base64'])
    .controller('myController', [

        '$base64', '$scope', 
        function($base64, $scope) {

            $scope.encoded = $base64.encode('a string');
            $scope.decoded = $base64.decode('YSBzdHJpbmc=');
    }]);

You could do this:

 var fileReader = new FileReader();
    fileReader.onload = function(e)
    {
        // e.target.result contains the "string" of your file
    };
    fileReader.readAsText(yourfile);
Share:
14,922
aqarain
Author by

aqarain

Updated on June 09, 2022

Comments

  • aqarain
    aqarain almost 2 years

    I am new to ionic and angular and right now I m trying to convert a file to base64 string. I am selecting file using cordova file plugin and the file could be image, pdf, doc or of any type. I have the full path to that file. How can I get the base64 string of that file? Can I use the file path to convert to base64 or what is the way to achieve this.

  • aqarain
    aqarain about 8 years
    Firstly, Thanks a lot Alex. but what should be the param, it takes string as param but I have pdf/img file path as param so how and what should I pass as param?
  • aqarain
    aqarain about 8 years
    Thanks @WebDevNewbieGirl, what is file in this?
  • aqarain
    aqarain about 8 years
    Thanks a lot com.ulf. but what should be the param, it takes string as param but I have pdf/img file path as param so how and what should I pass as param?
  • JF it
    JF it about 8 years
    Link only answers arent great - consider adding detail from both links in particular for this answer.
  • WebDevNewbieGirl
    WebDevNewbieGirl about 8 years
    In my case that was a picture(object) encoded binary form. For other types I cannot guarantee if this solution will work.
  • Sunil Lama
    Sunil Lama about 8 years
    If the param is image, you get the base64 encoded image and if the param is string you get the base64 encoded string.
  • aqarain
    aqarain about 8 years
    Thanks Harrish ;) The simplest, easiest and to the point solution
  • Zohra Gadiwala
    Zohra Gadiwala almost 7 years
    it is not working for pdf files and returning empty string.