Skip to content

Instantly share code, notes, and snippets.

@jmcarp
Created March 1, 2014 15:35
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jmcarp/9291539 to your computer and use it in GitHub Desktop.
Save jmcarp/9291539 to your computer and use it in GitHub Desktop.
Forcing a file download in JavaScript
function forceDownload(href) {
var anchor = document.createElement('a');
anchor.href = href;
anchor.download = href;
document.body.appendChild(anchor);
anchor.click();
}
@litefast
Copy link

How to use it?

@Rourke101
Copy link

This is absurd. You better place the download attribute yourself

@DaveSimmons1234
Copy link

Works perfectly. I don't think is absurd at all.

@PHPManager133
Copy link

PHPManager133 commented Jan 23, 2020

Doesn't work for me. Opening the image in same window rather than downloading.

@MakingCG
Copy link

MakingCG commented Feb 8, 2020

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/

@mikhsanh55
Copy link

Great!, maybe it seem better add line that remove the created element for clean code

@onny
Copy link

onny commented Feb 6, 2021

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 :(

@gryphon2411
Copy link

Don't forget to add document.body.removeChild(anchor); below anchor.click() line.

@abdessamadely
Copy link

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>

@akas089
Copy link

akas089 commented Aug 4, 2022

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