Ionic: Converting video to base64

I am going to assume for this article, that you are going to be receiving a file URI path from whatever plugin you are using for capturing/selecting videos in your Ionic application.

Install the plugin cordova-plugin-file

ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file

Import the plugin into your app.module like you would any other plugin.

In the .ts file that you’re going to convert the video to base64, import the plugin:

import { File, DirectoryEntry, FileEntry } from '@ionic-native/file';
...
constructor(private file: File) {
}
...

Now in that same .ts file, add the following function:

/*
* Reads the fileURI, uses FileReader() to encode it to base64, and then we have to fix it.
*/
private async convertVideoToBase64(video) {
return new Promise(async (resolve) => {
let res:any = await this.file.resolveLocalFilesystemUrl(video);
res.file((resFile) => {
let reader = new FileReader();
reader.readAsDataURL(resFile);
reader.onloadend = async (evt: any) => {
let encodingType = "data:video/mp4;base64,";
/*
* File reader provides us with an incorrectly encoded base64 string.
* So we have to fix it, in order to upload it correctly.
*/
let OriginalBase64 = evt.target.result.split(',')[1]; // Remove the "data:video..." string.
let decodedBase64 = atob(OriginalBase64); // Decode the incorrectly encoded base64 string.
let encodedBase64 = btoa(decodedBase64); // re-encode the base64 string (correctly).
let newBase64 = encodingType + encodedBase64; // Add the encodingType to the string.
resolve(newBase64);
}
});
});
}

I have tried to comment out the code as best as I can to explain what we are doing, basically, the native FileReader encodes the base64 incorrectly, so we have to decode it and then re-encoded it ourselves. (A bit hacky, i know, but it’s the best solution atm).

Now when you call the function convertVideoTobase64, you will be returned a promise with the base64 encoded video.

Questions?

You can find me on:
- GitHub: https://github.com/bengejd/
- Medium: https://medium.com/@JordanBenge

Who am I? I am a Software Developer who loves helping others and contributing to Open-Source. I’ve been working in the Ionic Framework since Ionic 1, and have tried to keep up to date on the latest and greatest when it comes to Hybrid Mobile App Development. If you found this article helpful, give it a clap, which helps encourage me to keep writing.