The download attribute of the <a> and <area> tags downloads a linked resource.
Definition and Usage
➔ It is possible to specify a filename for the downloaded file, otherwise the download will use its original filename. The browser will automatically detect the correct file extension.
➔ For security reasons, the download attribute only works for resources of the same origin (same domain, protocol, and port).
Syntax
//In HTML
<img src="myimage.png" width="350" height="250"><br>
<a id="sample" href="myimage.png" download='newfilename'>Download this image file</a>
//In Javascript
<script>
let element = document.querySelector("#sample");
element.download = ""; //original file name
element.download = "customname"; // rename downloaded file
</script>
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML download attribute example</title>
<style>
.mydiv {
border: 2px solid black;
padding: 30px;
background: rgb(100, 100, 100, 0.3);
}
</style>
</head>
<body>
<div class="mydiv">
<h3>HTML download attribute example</h3>
<p>The download attribute downloads a linked resource.</p>
<img src="./resources/images/workplace2.png" width="350" height="200"><br>
<a id="sample" href="./resources/images/workplace2.png" download='newfilename'>Download this image file</a>
</div>
<script>
// let element = document.querySelector("#sample");
// element.download = ""; //original file name
//element.download = "customname"; // rename downloaded file
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.