Javascript read file without using input

user986959 picture user986959 · Jan 14, 2014 · Viewed 25.7k times · Source

I have this code and for a file to be converted into base64 I have to click on Choose file and then select it. I want to hardcode the file name so it is converted to base64 on page load.

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: Thank you for your answers, they were really helpful.

Answer

asm00 picture asm00 · Jan 14, 2014

You simply can't 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 resolve the C:\fakepath?