Javascript read file without input

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.

+7
javascript input file onload
source share
2 answers

You simply cannot do what you are trying to do. Setting the path for an input element through Javascript is not possible, as a security measure. Please check here: How to enable C: \ fakepath?

+3
source share

You can run Chrome, a chrome browser with the --allow-file-access-from-files flag --allow-file-access-from-files , use fetch() of XMLHttpRequest() to request a file from the local file system.

 fetch("file:///path/to/file") .then(response => response.arrayBuffer()) .then(ab => { // do stuff with `ArrayBuffer` representation of file }) .catch(err => console.log(err)); 

See Also Read Local XML Using JS

+2
source share

All Articles