Wednesday, July 11, 2012

Serverless Downloads - HTML5 Awesomeness!

HTML5 brings an awesome feature known as client downloads. At first glance, the term "serverless downloads" may sound oxymoronic, but it sure makes a lot of sense. In the HTML5 era, we write a lot of thick clients. All the day to day web apps which we use are damn thick (Gmail, Facebook, etc.). So in the context of thick clients, serverless downloads make a lot of sense.

Content-Disposition HTTP Header

On the web 2.0 days, when you wanted to force a browser to download a file to disk rather than displaying it (especially if the file is of some format which the browser is capable of rendering), you used to set the Content-disposition header in the HTTP response.
Content-Disposition: attachment; filename="sample.txt";
There is no way for the browser to let the user download the file without contacting the server, even if the contents of the file were to be generated totally on the client side.

The Problem

This is old school. These days there are lot of web apps where you create the data on the app itself. For example, consider Google Docs, you create all sorts of documents on the web. Every time you click the download button, the data is sent to the server and the same data comes back along with required filetype's additions and you see the download dialog box.

This step seems too radical and unnecessary. Given how thick the clients are these days, it is atrocious to send some data to the server and get back the same data as a file from the server. The same holds for all sorts of web based photo editing apps, etc.

The Solution - "download" attribute

Now with HTML5 it is possible to generate a file on the client side and make the user download it without contacting the server at all. The simple addition of "download" attribute to the anchor(a) tag will tell the browser to download the content present in the "href" attribute rather than navigating it. Now, this can be combined with a "blob:" or a base64 encoded data url to create a file and download it, all on the client side.

I have put up a demo where you can enter text into a field and then download it as a pdf.

Image Courtesy: