Read files in JavaScript and HTML5

Actually I met with this issue for years. However, the modern solutions allow us really to approach this issue in a meaningful way, not related to one specific browser.

Read files in JavaScript and HTML5

Among the easiest ways, we can mention loading the file contents via AJAX; in case of jQuery we can use the get() method:

jQuery.get('test.txt', function(data) {
  alert(data);
  // process …
  // $('#mydiv').html(data.replace('n', '<br />'));
});

On-line example:

http://dominik-w.pl/tester_file_read.html

Valorant cheat

Be aware about limitations of this method (access to files on the local file system), as well as issues related with Same-origin policy.

During the various works with HTML5 Canvas, I met with the code as shown below, which acted as it should be, and in different browsers (newer versions).

Example — read image file in JavaScript and display on HTML5 Canvas

function loadImage() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  var imgSrc =
    'http://dominik-w.pl/direct-code-logo-company-200x.png';

  // add file:// if user specified local path
  if (imgSrc.indexOf("//") == -1 && imgSrc.indexOf(".") != 0) {
    imgSrc = "file:///" + imgSrc;
  }

  // load file into canvas and adjust params
  var img = new Image();
  img.onload = function() {
    width = img.width;
    height = img.height;
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0);

    // get image data
    try {
      imageData = ctx.getImageData(0, 0, width, height);
    } catch(e) {
      // !
      netscape.security.PrivilegeManager.
        enablePrivilege("UniversalBrowserRead");
      imageData = ctx.getImageData(0, 0, width, height);
    }
  }

  img.src = imgSrc;
}

The code works very well; canvas area adapts to the size of the image.

Read file in JavaScript

A full example on GitHub:

https://github.com/dominik-w/js_html5_com/blob/master/tester_canvas_file.html

Additional resources

By the way, there’s a lot of interesting solution to work with files in JavaScript, for example:

– FileAPI

http://mailru.github.io/FileAPI/

– WebKit and working with files

http://www.noupe.com/webdev/html5-filesystem-api-create-files-store-locally-using-javascript-webkit.html

– Reading Files Using The HTML5 FileReader API (teamtreehouse.com)

http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

– Using files from web applications (MDN):

https://developer.mozilla.org/pl/docs/Using_files_from_web_applications

– Binary — working with binary files in JavaScript:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

– Binary.js!

http://binaryjs.com/

Summary

Short and to the point. As you can see, at present there are no major problems to work with files from JavaScript and HTML5 level.

Have fun!