Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  14] [ 3]  / answers: 1 / hits: 5492  / 2 Years ago, wed, february 2, 2022, 12:00:00

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 onload=myFunction()>


</body>
</html>




More From » html

 Answers
1



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 onload=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


[#415] Wednesday, January 26, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamaal

Total Points: 515
Total Questions: 102
Total Answers: 107

Location: France
Member since Thu, May 6, 2021
3 Years ago
;