Skip to content

Instantly share code, notes, and snippets.

@narainsagar
Created December 8, 2016 15:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save narainsagar/08a61bace498b909f7ef339f3e60c9bc to your computer and use it in GitHub Desktop.
Save narainsagar/08a61bace498b909f7ef339f3e60c9bc to your computer and use it in GitHub Desktop.
Download a file with custom data and filename into browser (via Pure JS)

Define below method:

i.e., I have created this for my angular2 app. so this function is written in TypeScript

  createDownloadLink(filename: string, data: string) {
    var dataUri = 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(data);
    var anchor = document.createElement('a');

    anchor.setAttribute('href', dataUri);
    anchor.setAttribute('download', filename);
    // anchor.appendChild(document.createTextNode("Click to download your file."));

    // creates: <a href="data:application/octet-stream,DATA" download="FILENAME">TITLE</a>
    return anchor;
  }

Usage:

createDownloadLink('hello.json', '{"name": "Hello World"}').click();

Ref:

http://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser https://github.com/fhinkel/create-download-link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment