最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Download image from URL on page load using Javascript - Stack Overflow

programmeradmin1浏览0评论

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 = '@._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>

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./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>

Share Improve this question asked Feb 2, 2022 at 2:06 santosh santosh 8921 gold badge11 silver badges22 bronze badges 4
  • What do you mean by "not working" — What do you expect to happen? What actually happens? – Stephen P Commented Feb 2, 2022 at 2:09
  • I want the image should be downloaded on page load. – santosh Commented Feb 2, 2022 at 2:11
  • What do you mean by "download"? Si you want it to be fetched by the browser and shown in the page? (If so, why to use JavaScript instead of an img tag) or do you want the image to download as a file? – Daniel Cruz Commented Feb 2, 2022 at 2:42
  • I want the image to download as a file on page load! – santosh Commented Feb 2, 2022 at 2:55
Add a ment  | 

1 Answer 1

Reset to default 3

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./images/M/MV5BMTAxMGRmODYtM2NkYS00ZGRlLWE1MWItYjI1MzIwNjQwN2RiXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg', 'Download.jpg')" >DOWNLOAD</button>

<body onload="downloadImage('https://m.media-amazon./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

发布评论

评论列表(0)

  1. 暂无评论