Skip to content

Instantly share code, notes, and snippets.

@jmcarp
Created March 1, 2014 15:35
Show Gist options
  • Save jmcarp/9291539 to your computer and use it in GitHub Desktop.
Save jmcarp/9291539 to your computer and use it in GitHub Desktop.
Forcing a file download in JavaScript
function forceDownload(href) {
var anchor = document.createElement('a');
anchor.href = href;
anchor.download = href;
document.body.appendChild(anchor);
anchor.click();
}
@netojose
Copy link

A better way will be to show a link in your UI, so the user can click to download That way is safer from getting blocked something like:

<a href="attachment_url" download="attachment_url" target="_blank">Download</a>

Remember: This only works if the download url is in the same domain as you application.

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