Created
February 12, 2020 05:48
-
-
Save darrenmothersele/e015ef13b96d26d778161cbc56b6a5f5 to your computer and use it in GitHub Desktop.
Download a file in JavaScript/TypeScript (click handler for a button)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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