Skip to content

Instantly share code, notes, and snippets.

@nghiepdev
Last active May 29, 2018 16:46
Show Gist options
  • Save nghiepdev/34864e674de7c37d0464fc51228b5084 to your computer and use it in GitHub Desktop.
Save nghiepdev/34864e674de7c37d0464fc51228b5084 to your computer and use it in GitHub Desktop.
Force download file (via Ajax)
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