Read files in JavaScript and HTML5

Level: advanced

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) {
  // process ...
  // $('#mydiv').html(data.replace('n', '<br />'));

On-line example:

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 = 

  // 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) {
      // !
      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:

Additional resources

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

– FileAPI

– WebKit and working with files

– Reading Files Using The HTML5 FileReader API (

– Using files from web applications (MDN):

– Binary – working with binary files in JavaScript:

– Binary.js!


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!

Both comments and pings are currently closed.

Comments are closed.