Skip to content

Instantly share code, notes, and snippets.

@mckaydavis
Last active September 14, 2015 19:25
Show Gist options
  • Save mckaydavis/54ae1c9d648bd419abdb to your computer and use it in GitHub Desktop.
Save mckaydavis/54ae1c9d648bd419abdb to your computer and use it in GitHub Desktop.
Start browser download of 'data' (or text) as the specified filename and mime type
// McKay Davis / 2015
// triggerBrowserDownloadOfDataAsFilename(data, filename = 'download', mimetype = 'text/plain')
//
// Start browser download of 'data' as the specified filename and mime type
// if 'data' is already a dataURL, it will not be encoded and 'mimetype' will be ignored
// if not specified, 'filename' will default to 'download'
// if not specified, 'mimetype' will default to 'text/plain'
//
// example:
// triggerBrowserDownloadOfDataAsFilename('Hello World!\n', 'hello.txt');
//
// if data is already a dataURL:
// triggerBrowserDownloadOfDataAsFilename(canvas.toDataURL('image/png'), 'canvas.png');
//
function triggerBrowserDownloadOfDataAsFilename(data, filename, mimetype){
var elem = document.createElement('a');
elem.href = data.substr(0,5) === 'data:' ? data :
['data:',
mimetype !== undefined ? mimetype : 'text/plain',
';base64,',
window.btoa(data)
].join("");
elem.setAttribute('download', filename !== undefined ? filename : 'download');
elem.click();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment