3

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
aqarain
  • 43
  • 1
  • 1
  • 8

5 Answers5

2

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

Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28
1

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>
Sunil Lama
  • 4,531
  • 1
  • 18
  • 46
  • 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 Feb 22 '16 at 09:11
  • 1
    If the param is image, you get the base64 encoded image and if the param is string you get the base64 encoded string. – Sunil Lama Feb 22 '16 at 09:19
1

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);
com.ulf
  • 11
  • 3
  • 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? – aqarain Feb 22 '16 at 09:14
  • Link only answers arent great - consider adding detail from both links in particular for this answer. – JF it Feb 22 '16 at 09:19
0

try with

file.toString('base64');

you can also try reading these since it is basically a framework build on JS

Base64 encoding and decoding in client-side Javascript

Community
  • 1
  • 1