Upload Image and Covert To The Base64 String by Using Javascript

In this post, Upload Image and Covert To The Base64 String by Using Javascript , you will learn how to convert uploaded image into Base64 string.

Base64 encoded Format : data:image/png;base64,8UIOINSHVBORw0KG467JYSGHSKGSFAAAANSUhEUgAHJSKJSKUGBHSH

Base64 is a binary-to-text encoding techniques that encode binary data into 24-bit sequences that can be represented by four 6-bit Base64 digits.

 

<!DOCTYPE html>
<html lang="en">
<input type="file" id="upload_file" name="upload_file"><br>

<p id="base64"></p><br>
<img id="uploaded_image"><br>

<script>
function uploadFile() {
  console.log('here');
  if (!this.files || !this.files[0]) return;
    
  const fileReader = new FileReader();
    
  fileReader.addEventListener("load", function(evt) {
    document.querySelector("#uploaded_image").src = evt.target.result;
    document.querySelector("#base64").textContent = evt.target.result;
  }); 
    
  fileReader.readAsDataURL(this.files[0]);
}
document.querySelector("#upload_file").addEventListener("change", uploadFile);
</script>
</html>

Output:

 

I hope this post helped you to learn about Upload Image and Covert To The Javaby Using Javascript in a very detailed way.