1

Having HTML document with Javascript code loaded from a local .html file (file:///C:/...) is there any way in pure Javascript (no jQuery) to read local .txt file with all major browsers without adding any flag, such as --allow-file-access-from-files in Chrome, etc.?

4
  • 2
    First result on Google: html5rocks.com/en/tutorials/file/dndfiles Commented Jul 18, 2012 at 17:22
  • @Ωmega Of course it works with Chrome! I did not add any special flags.
    – Naftali
    Commented Jul 18, 2012 at 17:26
  • 2
    @Ωmega As a matter of fact, it is. Commented Jul 18, 2012 at 17:26
  • If you want to include IE as a "major browser", I'm sure you will need to use ActiveX.
    – Bergi
    Commented Jul 18, 2012 at 17:30

1 Answer 1

1

You can do this only with HTML5

Example from that site:

<style>
  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }
</style>

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
2
  • 1
    onload is not fired in Chrome.
    – Ωmega
    Commented Jul 18, 2012 at 17:26
  • @Ωmega it perfectly fine for me on Chrome :-)
    – Naftali
    Commented Jul 18, 2012 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.