-
-
Save jmcarp/9291539 to your computer and use it in GitHub Desktop.
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
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.
Great!, maybe it seem better add line that remove the created element for clean code