Data, Maps, Usability, and Performance

HTML5 download attribute with JavaScript

Last updated on July 19, 2012 in Development

HTML5 download attribute

The other day I wanted to download all my flickr photos with a simple click instead of doing it individually. I looked around for some flickr profile downloaders but was not really impressed with the results, and in my opinion, I should just be able to do this in the browser. First of all, I should be able to just download any file by clicking on it once (instead of right clicking, choosing where to save it, etc). And secondly, if I want to download multiple files at once, I should be able to create a JavaScript function that will do this.

Unfortunately, most browsers will not let you do this on the client side. On the server side, you could specify an HTTP-Header with a mime-type but this does not work for files you don’t own. The good new is that Chrome, my favorite browser, allows client-side download forcing with the support of the HTML5 download attribute (Chrome supports it since version 14).

Here is the spec for the download attribute and it works by adding the attribute to a link with a reference to the path of the file you want download, for example:

<a href="path-to-file.png" download="path-to-file.png">Download file</a>

Here is a real life example that you can test in Chrome, just click on the image with your mouse:

HTML5 download attribute

This is the code for the image above:

<a href="" download=""><img src="" alt="HTML5 download attribute"></a>

Pretty cool. But, I want to execute the download through JavaScript, and I want to download multiple files with one click. Let’s say I have a page with images, it could be my page with images loaded from external servers, or just a flickr page where I can execute some JavaScript code in the console or in a chrome extension. The JavaScript needs to execute a click event on each link and it needs to be a native click event, not something like a jQuery click(). Here’s one way to get it done, view the source and then try it by clicking the download all link.

There are also other use cases for this download attribute, like working with “blob: URLs” and “filesystem: URLs.” HTML5rocks talks about it here and Mathias Bynens also writes about it in his blog.

Tags: ,

Facebook Twitter Hacker News Reddit More...