Learn how to download images from any URL using the fetch() API in JavaScript.
Source Code:
//index.html
<!doctype html>
<html lang="en-US" >
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes">
<title>Download Image from URL using fetch</title>
</head>
<body>
<p><h1>Download Image from URL using fetch</h1></p>
<button id="downloadImage"> Download Image </button>
<script>
const btn = document.getElementById('downloadImage');
const url = "img/photo001.jpg";
btn.addEventListener('click', (event) => {
event.preventDefault();
console.log(url)
downloadImage(url);
})
function downloadImage(url) {
fetch(url, {
mode : 'no-cors',
})
.then(response => response.blob())
.then(blob => {
let blobUrl = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.download = url.replace(/^.*[\\\/]/, '');
a.href = blobUrl;
document.body.appendChild(a);
a.click();
a.remove();
})
}
</script>
</body>
</html>
Source Code : https://tutorial101.blogspot.com/2022/06/download-image-from-url-using-fetch.html