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);
Author by
aqarain
Updated on June 09, 2022Comments
-
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 about 8 yearsFirstly, 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 about 8 yearsThanks @WebDevNewbieGirl, what is file in this?
-
aqarain about 8 yearsThanks 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 about 8 yearsLink only answers arent great - consider adding detail from both links in particular for this answer.
-
WebDevNewbieGirl about 8 yearsIn my case that was a picture(object) encoded binary form. For other types I cannot guarantee if this solution will work.
-
Sunil Lama about 8 yearsIf the param is image, you get the base64 encoded image and if the param is string you get the base64 encoded string.
-
aqarain about 8 yearsThanks Harrish ;) The simplest, easiest and to the point solution
-
Zohra Gadiwala almost 7 yearsit is not working for pdf files and returning empty string.