how to download image on button click using javascript

how to download image on button click using javascript – we will download images and file using FileSaver.min.js. Download and put the FileSaver.js after the latest jQuery library.

How to Download Image on Button Click Using Javascript?

download file on button click in javascript (Open New Tab). Example click here

Instant download image on button click

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>how to download image on button click using javascript - www.pakainfo.com</title>
<style>
div {
    display: flex;
    flex-direction: column;
    align-items: center;
}

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

button {
    display: block;
    padding: 10px;
    margin-top: 10px;
}
</style>
</head>
<body>
    
    <div>
       <img src="https://i.imgur.com/sduLRvf.jpg" alt="File Download">
       <button>Download</button>
    </div>

<script src="js/FileSaver.min.js"></script>    
<script>
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 fldesname = img.getAttribute('src');
    let fileName = getFileName(fldesname);
    saveAs(fldesname, fileName);
});

function getFileName(str) {
    return str.substring(str.lastIndexOf('/') + 1)
}
</script>
</body>
</html>

I hope you get an idea about how to download image on button click using javascript.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, donโ€™t forget to share.