Created
March 1, 2014 15:35
-
-
Save jmcarp/9291539 to your computer and use it in GitHub Desktop.
Forcing a file download in JavaScript
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
function forceDownload(href) { | |
var anchor = document.createElement('a'); | |
anchor.href = href; | |
anchor.download = href; | |
document.body.appendChild(anchor); | |
anchor.click(); | |
} |
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 :(
Don't forget to add document.body.removeChild(anchor);
below anchor.click()
line.
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>
Not work download but view image in page
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great!, maybe it seem better add line that remove the created element for clean code