Chapter 7. Working with Files

Traditionally, file access and manipulation was within the realm of desktop apps, with the Web limited to functionality provided by plug-in technologies like Adobe Flash. However, all of that is changing with HTML5, which gives developers a lot more scope for dealing with files, further blurring the boundaries between desktop and the Web. With modern browsers, users can drag and drop files onto the page, paste structured data, and see real-time progress bars as files upload in the background.

Browser Support

Support for the new HTML5 file APIs is not universal, but certainly enough browsers have implementations that it’s worth your while to integrate them.

  • Firefox >= 3.6

  • Safari >= 6.0

  • Chrome >= 7.0

  • IE: no support

  • Opera >= 11.1

As there’s no IE support yet, you’ll have to use progressive enhancement. Give users the option of a traditional file input for uploading, as well as allowing the more advanced drag/dropping of files. Detecting support is simple—just check whether the relevant objects are present:

if (window.File && window.FileReader && window.FileList) {
  // API supported
}

Getting Information About Files

The main security consideration behind HTML5’s file handling is that only files selected by the user can be accessed. This can be done by dragging the file onto the browser, selecting it in a file input, or pasting it into a web application. Although there has been some work to expose a filesystem to JavaScript, access has always been sandboxed. Obviously, ...

Get JavaScript Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.