-
-
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(); | |
} |
Works perfectly. I don't think is absurd at all.
Doesn't work for me. Opening the image in same window rather than downloading.
Doesn't work for me. Opening the image in same window rather than downloading.
To force download your file, you have to set in http response header with 'Content-Disposition' property, for more info, you can visit this article https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/
Great!, maybe it seem better add line that remove the created element for clean code
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.
This is absurd. You better place the download attribute yourself