I want when page load my image must be downloaded based on URL! But my following code is not working please help!
Code:
function myFunction() {
var link = document.createElement('a');
link.href = 'https://m.media-amazon.com/images/M/MV5BMTAxMGRmODYtM2NkYS00ZGRlLWE1MWItYjI1MzIwNjQwN2RiXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
<!DOCTYPE html>
<html>
<body onl oad="myFunction()">
</body>
</html>
CodePudding user response:
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'));
}
<button onclick="downloadImage('https://m.media-amazon.com/images/M/MV5BMTAxMGRmODYtM2NkYS00ZGRlLWE1MWItYjI1MzIwNjQwN2RiXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg', 'Download.jpg')" >DOWNLOAD</button>
<body onl oad="downloadImage('https://m.media-amazon.com/images/M/MV5BMTAxMGRmODYtM2NkYS00ZGRlLWE1MWItYjI1MzIwNjQwN2RiXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg', 'Download.jpg')">
NOTE: I am not sure why the "Run Code Snippet" is not working so please check the solution in code pen https://codepen.io/Gopi-Veeramani/pen/KKyzoJL
