Javascript Downloads

Code Snippets Downloads
Share:

About

In this code snippet, we’ll learn how to perform downloads with Javascript.

File downloads can be programmatically started with javascript by creating a temporary link element that points to your file. Then you add it to the DOM and call its click function to initiate the download. Finally, you can remove the link.

Let’s see how to do it in the example below.

Code:

index.html
Nothing exciting here, this HTML is used just so we can add and run the code.js file for this demo.
<!DOCTYPE html>
<html>
<head>
<title>File Download</title>
</head>
<script src="code.js"></script>
<body>
<div>
<h1>File Download</h1>
</div>
</body>
</html>
code.js
//Run this when the HTML gets loaded.
window.onload = () => {
//Here I'll be downloading an image stored locally. But it could be any type of file from any url(with CORS enabled).
downloadUrl("Code Snippets Downloads.png", "PostCoverImage.png"); //downloadUrl(url, file name, does it open in new tab or not)
}
async function downloadUrl(url, fileName){
//Get blob from url. 
let blob = await fetch(url).then(res => res.blob());
//Creates temp. url for the blob.
const download = window.URL.createObjectURL(blob);
//Create temp. link for download.
var link = document.createElement('a');
//Add data.
link.href = download;
//Set file name.
link.download = fileName;
//Execute download by clicking the link programatically.
link.click();
setTimeout(function(){
//For Firefox it is necessary to delay revoking the ObjectURL.
window.URL.revokeObjectURL(download);
}, 100);
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger