close

How to convert file to base64 in JavaScript?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to convert file to base64 in JavaScript? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to convert file to base64 in JavaScript ?

  1. How to convert file to base64 in JavaScript ?

    to convert file to base64 in JavaScript TypeScript version
    const file2Base64 = (file:File):Promise<string> => { return new Promise<string> ((resolve,reject)=> { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result.toString()); reader.onerror = error => reject(error); }) }

  2. How to convert file to base64 in JavaScript ?

    to convert file to base64 in JavaScript TypeScript version
    const file2Base64 = (file:File):Promise<string> => { return new Promise<string> ((resolve,reject)=> { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result.toString()); reader.onerror = error => reject(error); }) }

Method 1

Modern ES6 way (async/await)

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();

UPD:

If you want to catch errors

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   const result = await toBase64(file).catch(e => Error(e));
   if(result instanceof Error) {
      console.log('Error: ', result.message);
      return;
   }
   //...
}

Method 2

TypeScript version

const file2Base64 = (file:File):Promise<string> => {
    return new Promise<string> ((resolve,reject)=> {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result.toString());
         reader.onerror = error => reject(error);
     })
    }

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment