Skip to content

Instantly share code, notes, and snippets.

@lzbgt
Created February 17, 2022 03:19
Show Gist options
  • Save lzbgt/3580de957f0b20354c663bbf6962d6e0 to your computer and use it in GitHub Desktop.
Save lzbgt/3580de957f0b20354c663bbf6962d6e0 to your computer and use it in GitHub Desktop.
Force image download with JavaScript
<a href="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Stack_Overflow_logo.svg/1280px-Stack_Overflow_logo.svg.png" download="Logo.png" >DOWNLOAD (only open)</a>
<br><br>
<button onclick="downloadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Stack_Overflow_logo.svg/1280px-Stack_Overflow_logo.svg.png', 'LogoStackOverflow.png')" >DOWNLOAD (forced)</button>
function downloadImage(url, name){
fetch(url)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch(() => alert('An error sorry'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment