HTML5 Download Attribute: Success!

HTML5 Download Attribute Success Meme

Providing direct and easy download of files can be simplified using the HTML5 download attribute. Historically, forcing a browser to save a file has been an over complicated programming task. New HTML5 specifications have identified this gap in browser technology and have mapped out a straightforward approach to downloading resources using the new download attribute on anchor and area elements. In this post, I will briefly outline the challenges that developers had before the download attribute was available and then show how simple it is to implement.

Direct Download Challenges

Historically, there have been a number of different methods developers could try to employ to force a file to be downloaded in the browser. One popular choice is to use JavaScript to open a new window pointed at the file. Unfortunately, if the Content Type header of the HTTP response from the server is a MIME Type that the browser knows how to handle, the browser will simply open the file in the newly opened browser window. This approach can work for files that a browser is not used to handling (executables etc.) but will not work for common web files like images.

docuement.getElementById("download-button").addEventListener("click", function() {
            window.open(urlToFileLocation);
        });

Another more complicated approach involves writing server side code (C#, PHP, Java) that would receive an HTTP request, process it based on whatever logic is needed, and return a response that included the file with a Content-Disposition field set to attachment. This is a more reliable approach and can handle any file type the server is capable of serving up, but requires access to server side code and greater level of effort.

// ASP.NET C# Example
Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/octet-stream";
Response.WriteFile(filePath);
Response.Flush();
Response.End();

The download attribute

(At the time of this writing, the feature is not available in IE or Safari. Click here for existing support.)

Thankfully, with new HTML5 specifications for Downloading Resources, this additional effort can now be avoided by adding a single download attribute to any link.

<a href="download-success.jpg" download>Download Meme</a>

Here is the above link in action:  Download Meme

This approach is very straightforward and has the potential to save time and headaches for developers moving forward. Support for IE and Safari is still missing, but since the the target file is referenced in the href of the link, if a browser is missing support for the download attribute, it will attempt request the file like any other link.