How to Convert image to base64 string using JavaScript

 22 - Jan - 2022
 XpertPhp
 39

In this tutorial, we will explain to you How to Convert image to base64 string using JavaScript. we can easily Convert image to base64 string in javascript. Now we create onchange event and this will execute a function encodeBase64() when you upload an image. so you can see our example. Example

<!DOCTYPE html>
<html>
<head>
  <title>How to Convert image to base64 string using JavaScript</title>
  <script type="text/javascript">
    function encodeBase64(elm) {
		  var file = elm.files[0];
		  var imgReader = new FileReader();
		  imgReader.onloadend = function() {
			console.log('Base64 Format', imgReader.result);
		  }
		  imgReader.readAsDataURL(file);
	}
  </script>
</head>
<body>
  <form>
     <input type="file" onchange="encodeBase64(this)" />
  </form>  
</body>
</html>