article

Thursday, June 2, 2022

Download Image from URL using fetch

Download Image from URL using fetch

//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>

Related Post