How to get data in Base64 from input file data?

This is how we read the file data from the input form, how can I get Base64 from the fileList ?

HTML

 <form action="upload.php" method="POST" id="uploadform"> <input id="uploadBtn" type="file" name="file"/> <input type="submit" value="Upload"/><br/><br/> </form> 

Js

 var inputElement = document.getElementById("uploadBtn"); inputElement.addEventListener("change", handleFiles, false); function handleFiles() { var fileList = this.files; } 
  • Why can base64 file be useful on the client side? - UserName

1 answer 1

You can read the file using FileReader() , and take the result in Base64 from the result target.result field.

 function handleFiles() { var reader = new FileReader(), input = document.getElementById('input').files[0], output = document.getElementById('output'); reader.addEventListener("loadend", function(result) { output.innerHTML = result.target.result; }, false); reader.readAsDataURL(input); } 
 <input id="input" type="file" onchange="handleFiles()" /> <p id="output"></p> 

  • Do you think this is a cross-browser option? - gilo1212
  • @ gilo1212, look here - UserName
  • @UserName Understand. Thank. In general, IE 9 and less support. - gilo1212