How to Download Image on Button Click Using Javascript

In this video tutorial, you will learn how to download image on button click using javascript.  We are going to use FileSaver.js to accomplish the job. This library will help you download any kind of file using javascript. I recommend you go through their docs to learn how efficiently you can use this.

At the time of creating tutorial, FileSaver.js v2.0.3 has some issues, so I am using v2.0.2 here.  May be they will fix the bug in the future and you can use the latest one.  You can download this library or you can use CDN link.  I have downloaded it and included it using script tag in the HTML. You can copy HTML, Javascript, CSS code given below.

 

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
       <img src="https://i.imgur.com/sduLRvf.jpg" alt="">
       <button>Download</button>
    </div>

    <script src="js/FileSaver.min.js"></script>
    <script src="js/script.js"></script>
</body>
</html>

 

CSS:

div {
    display: flex;
    flex-direction: column;
    align-items: center;
}

img {
    height: 400px;
    width: 400px;
}

button {
    display: block;
    padding: 10px;
    margin-top: 10px;
}

 

Javascript:

let btnDownload = document.querySelector('button');
let img = document.querySelector('img');


// Must use FileSaver.js 2.0.2 because 2.0.3 has issues.
btnDownload.addEventListener('click', () => {
    let imagePath = img.getAttribute('src');
    let fileName = getFileName(imagePath);
    saveAs(imagePath, fileName);
});

function getFileName(str) {
    return str.substring(str.lastIndexOf('/') + 1)
}

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •