Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@litefast litefast commented Jan 19, 2018

How to use it?

@Rourke101

This comment has been minimized.

Copy link

@Rourke101 Rourke101 commented Apr 20, 2019

This is absurd. You better place the download attribute yourself

@DaveSimmons1234

This comment has been minimized.

Copy link

@DaveSimmons1234 DaveSimmons1234 commented Jun 14, 2019

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

@PHPManager133

This comment has been minimized.

Copy link

@PHPManager133 PHPManager133 commented Jan 23, 2020

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

@MakingCG

This comment has been minimized.

Copy link

@MakingCG 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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.