Javascript Downloads

Code Snippets Downloads


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.


Nothing exciting here, this HTML is used just so we can add and run the code.js file for this demo.
<!DOCTYPE html>
        <title>File Download</title>
    <script src="code.js"></script>
            <h1>File Download</h1>
//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. = fileName;

  //Execute download by clicking the link programatically.;

    //For Firefox it is necessary to delay revoking the ObjectURL.
  }, 100);

Resulting output:


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