Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

Javascript read file without using input

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...