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
function readFile() {
if (!this.files || !this.files[0]) return;
const FR = new FileReader();
FR.addEventListener("load", function(evt) {
document.querySelector("#img").src = evt.target.result;
document.querySelector("#b64").textContent = evt.target.result;
});
FR.readAsDataURL(this.files[0]);
}
document.querySelector("#inp").addEventListener("change", readFile);
<input id="inp" type="file">
<p id="b64"></p>
<img id="img" height="150">
Related Topics
How to Apply the Length Condition on the Existing Regular Expression
What Does This Format Means T00:00:00.000Z
Javascript Updating Values of Objects Inside List
Stretch Height to Fit Content in React Native
How to Find Object in a List of Items by Index Using Es6 (Reactjs)
Websocket Connection Failed: Error During Websocket Handshake: Unexpected Response Code: 400
Calculate Time Difference Between Two Date in Hh:Mm:Ss JavaScript
Convert Time Stamp to Date Inside Angular Expression Like {{New Date(Timestamp)}}
Development Server of Create-React-App Does Not Auto Refresh
How to Reset the Bootstrap Modal When It Gets Closed and Open It Fresh Again
Clear an Input Field With Reactjs
Javascript String With New Line - But Not Using \N
How to Make a Bot React to Its Own Message
How to Play Audio File into Channel
Regex to Get String Between Curly Braces
How to Check a Radio Button in the Table Row Based on That Column Header