Skip to content

Instantly share code, notes, and snippets.

@darrenmothersele
Created February 12, 2020 05:48
Show Gist options
  • Save darrenmothersele/e015ef13b96d26d778161cbc56b6a5f5 to your computer and use it in GitHub Desktop.
Save darrenmothersele/e015ef13b96d26d778161cbc56b6a5f5 to your computer and use it in GitHub Desktop.
Download a file in JavaScript/TypeScript (click handler for a button)
import * as stringify from 'json-stringify-safe';
const format = 'json';
const outputData = stringify(this.model);
const mimeTypes = {
'json': 'application/json',
'csv': 'text/csv',
'xml': 'text/xml',
'txt': 'text/plain'
};
const blob = new Blob([outputData], { type: `${mimeTypes[format]};charset=utf-8;` });
const link = document.createElement('a');
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', `${this.fileName}.${format}`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment