JSFiddle - React, Tailwind, and code Playground
by dipeshbeckham
HTML
<button onClick="downloadResource('https://images.ctfassets.net/ol2f84o5hsfk/1dtgtSy7pbMbDNFKoNtRGU/80bfb9dd5899abd3ad34a7eb7aa09da7/24011083_s.jpg', 'download.png')">
Download Image
</button>
JavaScript
function forceDownload(blob, filename) {
const a = document.createElement('a');
a.download = filename;
a.href = blob;
document.body.appendChild(a);
a.click();
a.remove();
}
function downloadResource(url, filename) {
if (!filename) {
filename = url.split('\\').pop().split('/').pop();
}
fetch(url, {
headers: new Headers({
'Origin': location.origin
}),
mode: 'cors'
})
.then(response => response.blob())
.then(blob => {
let blobUrl = window.URL.createObjectURL(blob);
forceDownload(blobUrl, filename);
})
.catch(e => console.error(e));
}