Ionic 3: Converting video to base64

Jordan Benge
Oct 19, 2018 · 2 min read

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.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 =',')[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.

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.


You can find me on:
- GitHub:
- Medium:

Who am I? My name is Jordan Benge, 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 enjoyed this story, please click the 👏 button and share to help others find it! Feel free to leave a comment below if you need any help.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store