Save/Download file using HTML5 / JavaScript – The “download” Attribute

We usually write the code on server side and set the response header which will show the save dialog popup to download the file, when we try to open the file in another window url.

But, my requirements were that:

–          Mine was a HTML5/Javascript based client side application

–          Server side code was returning a Stream.

I investigated what methods there are to save data in JavaScript. I came up with the solution after some research on the HTML5 attributes. HTML5 has added the “download” attribute. It allows you to set a separate file download name than the actual link endpoint itself, which will attach with the anchor tag. It doesn’t use Flash or an echo server.

Code:-

 
<a href="#" download="data.csv" id="btnSave" >Export data into Excel</a>

And when the user clicks the link, the download attribute appears in the save. In this case, the file will be downloaded as “data.csv”.

HTML code :-

 
<!DOCTYPE html>

<head></head>

<body>

<div id="dvData">

<iframe id="myFrame" style="display:none"></iframe>

</div>

<br/>

<a href="#" download="data.csv" id="btnExport" >Export data into Excel</a>

</body>

</html>

Javascript :-

 
function exportToCSV() {

var csv = “Abc, DEF, GHI, JKLM”

// Data URI

csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

$(this)

.attr({

'href': csvData,

'target': '_blank'

});

}

// This must be a hyperlink

$("#btnExport ").on('click', function (event) {

exportToCSV.apply();

});

A caveat – Previous versions of Internet Explorer

The above code is supported for all the latest browsers except IE before the version 10.

So, for previous version of IE, we need to call “window.executeCommand” to save the file.

Javascript:-

 
function exportToCSV() {

var csv = “Abc, DEF, GHI, JKLM”

csvData = 'data:text/csv;charset=utf-8,' + csv;

//For IE

if (navigator.appName == "Microsoft Internet Explorer") {

myFrame.document.open("text/html", "replace");

myFrame.document.write(uuu);

myFrame.document.close();

myFrame.focus()

myFrame.document.execCommand('SaveAs', true, 'data.xls');

}

else {

//Others

$('#btnExport').attr({'href': csvData, 'target': '_blank' });

}

}

3 thoughts on “Save/Download file using HTML5 / JavaScript – The “download” Attribute

Leave a Reply

Your email address will not be published. Required fields are marked *


7 + eight =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>