Generate & Download File with JavaScript
Generate a simple CSV file using JavaScript.
HTML
<a href="data:application/octet-stream,https://www.google.co.in/imgres?imgurl=http://www.countercurrents.org/SavitribaiPhule.jpg&imgrefurl=http://www.countercurrents.org/chimurkar111215.htm&h=1238&w=898&tbnid=ZOj16hKhKsGoYM:&vet=1&tbnh=186&tbnw=134&docid=F8kwr6IXH6ub2M&itg=1&hl=en&usg=__1t5V-8kWS5c-9-vc6EecyHFDS5o=&sa=X&ved=0ahUKEwiI-ay1qqXRAhVCtI8KHSbJBYUQ_B0IqwEwGw">Link</a>
<br />
<h2></h2>
<button id="basic">Basic Implementation</button>
<br />
<h2></h2>
<button id="blob">Blob Implementation</button>
JavaScript
$( "#basic" ).click(function() {
window.open( "data:text/csv,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A" );
});
/* WIP */
$( "#blob" ).click(function() {
var data = [ { foo: "bar", goo: "gaa" }, { yep: "yeah", nope: "nah" } ];
download( data );
});
function setFile( data, fileName, fileType ) {
// Set objects for file generation.
var blob, url, a, extension;
// Get time stamp for fileName.
var stamp = new Date().getTime();
// Set MIME type and encoding.
fileType = ( fileType || "text/csv;charset=UTF-8" );
extension = fileType.split( "/" )[1].split( ";" )[0];
// Set file name.
fileName = ( fileName || "ActiveVoice_" + stamp + "." + extension );
// Set data on blob.
blob = new Blob( [ data ], { type: fileType } );
// Set view.
if ( blob ) {
// Read blob.
url = window.URL.createObjectURL( blob );
// Create link.
a = document.createElement( "a" );
// Set link on DOM.
document.body.appendChild( a );
// Set link's visibility.
a.style = "display: none";
// Set href on link.
a.href = url;
// Set file name on link.
a.download = fileName;
// Trigger click of link.
a.click();
// Clear.
window.URL.revokeObjectURL( url );
} else {
// Handle error.
}
}
function download( data ) {
var result = "",
headers = [],
header = "",
field = "";
// Process data.
$.each( data, function( index, rows ) {
// Set columns.
$.each( rows, function( name, column ) {
if ( column.value ) {
// Format header.
header = name;
// Set header if not already set.
if ( $.inArray( header, headers ) === -1 ) {
// Set column header and delimiter.
headers.push( header );
}
...