1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | //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> |
article
Thursday, June 2, 2022
Download Image from URL using fetch
Download Image from URL using fetch