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.
download file on button click in javascript (Open New Tab). Example click here
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.