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();
}
@onny
Copy link

onny commented Feb 6, 2021

This doesn't force download if the target file is for example an audio file. It starts playing directly in the browser without any download started :(

@gryphon2411
Copy link

Don't forget to add document.body.removeChild(anchor); below anchor.click() line.

@abdessamadely
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>

@akas089
Copy link

akas089 commented Aug 4, 2022

Not work download but view image in page

@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