Last active
May 29, 2018 16:46
-
-
Save nghiepdev/34864e674de7c37d0464fc51228b5084 to your computer and use it in GitHub Desktop.
Force download file (via Ajax)
This file contains hidden or 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
const url = "https://www.google.com.vn/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"; | |
const forceDownload = url => { | |
try { | |
const link = document.createElement('a'); | |
const fileName = url.substring(url.lastIndexOf('/') + 1, url.length); | |
const event = new MouseEvent( "click", { "button": 1, "which": 1 }); | |
link.href = url; | |
link.download = fileName; | |
link.dispatchEvent(event); | |
} catch(e) { | |
document.location = url; | |
} | |
} | |
forceDownload(url); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment