How to Convert File to Base64 in JavaScript

How to convert file to base64 in JavaScript?

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];
try {
const result = await toBase64(file);
return result
} catch(error) {
console.error(error);
return;
}
//...
}

Convert file to Base64

I think you have missed the return statement in the code.
Replace your function with the following lines:

var file = document.getElementById("file").files[0];
if (file) {
var filereader = new FileReader();
filereader.readAsDataURL(file);
filereader.onload = function (evt) {
var base64 = evt.target.result;
return base64
}

}

convert file to base64 in angular

Your code works fine. Are you sure you are correctly getting the file object?

Below is the stackblitz demo of the same.

Also, it better to use promise while reading files. You can use below function to read a file. It takes file as input and resolves to base64 string.

private readBase64(file): Promise<any> {
const reader = new FileReader();
const future = new Promise((resolve, reject) => {
reader.addEventListener('load', function () {
resolve(reader.result);
}, false);
reader.addEventListener('error', function (event) {
reject(event);
}, false);

reader.readAsDataURL(file);
});
return future;

}

Call this function as below -

this.readBase64(file)
.then((data) => {
// your code
});

How can I convert an image into Base64 string using JavaScript?

You can use the HTML5 <canvas> for it:

Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).

How to convert files to Base64 in React

file reading is asynchronous. so use callback or promise to solve your problem.

let idCardBase64 = '';
this.getBase64(idCard, (result) => {
idCardBase64 = result;
});

and use callback to return the data which you get.

getBase64(file, cb) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
cb(reader.result)
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}

Image convert to Base64