I have this code, and for the file that needs to be converted to base64, I have to click "Select File" and then select it. I want to copy the file name so that it is converted to base64 when the page loads.
JavaScript:
var handleFileSelect = function(evt) { var files = evt.target.files; var file = files[0]; if (files && file) { var reader = new FileReader(); reader.onload = function(readerEvt) { var binaryString = readerEvt.target.result; document.getElementById("base64textarea").value = btoa(binaryString); }; reader.readAsBinaryString(file); } if (window.File && window.FileReader && window.FileList && window.Blob) { document.getElementById('filePicker') .addEventListener('change', handleFileSelect, false); } else { alert('The File APIs are not fully supported in this browser.'); } };
HTML:
<div> <div> <label for="filePicker">Choose or drag a file:</label><br/> <input type="file" id="filePicker"> </div> </br> <div> <h1>Base64 encoded version</h1> <textarea id="base64textarea" placeholder="Base64 will appear here" cols="50" rows="15"> </textarea> </div> </div>
EDIT: Thanks for your answers, they were really helpful.
javascript input file onload
user986959
source share