Skip to content
Related Articles

Related Articles

Improve Article

How to convert image into base64 string using JavaScript ?

  • Last Updated : 12 Apr, 2021
Geek Week

Approach :

  • Here we will create a gfg.js file which will include or JavaScript code and one gfg.html file.
  • Now we will put onchange  on input type and this will execute a function  imageUploaded() when you upload an image.
  • Now we will use file reader and use onload event in file reader than we will get image url and we need to remove some text to get the base64 string and store in variable named base64String and print on console.
  • And if you want to use this base64 you can write logic on button click like here we will alert this base64 String.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src="gfg.js"></script>
</head>
  
<body>
    <input type="file" name="" id="fileId" 
        onchange="imageUploaded()">
    <br><br>
  
    <button onclick="displayString()">
        Display String
    </button>
</body>
  
</html>

Javascript




let base64String = "";
  
function imageUploaded() {
    var file = document.querySelector(
        'input[type=file]')['files'][0];
  
    var reader = new FileReader();
    console.log("next");
      
    reader.onload = function () {
        base64String = reader.result.replace("data:", "")
            .replace(/^.+,/, "");
  
        imageBase64Stringsep = base64String;
  
        // alert(imageBase64Stringsep);
        console.log(base64String);
    }
    reader.readAsDataURL(file);
}
  
function displayString() {
    console.log("Base64String about to be printed");
    alert(base64String);
}

Output:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :