简体   繁体   中英

failed network error when downloading images in javascript

When I try to download image on button click in javascript, am getting failed network error

function downloadImg(url, name){
    const link = document.createElement('a');
    link.href = `data:application/octet-stream;base64,${encodeURIComponent(url)}`;
    link.download = name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

}

<button onclick=this.downloadImg("http://www.example.com/image.png", "img1.png");>Download</button>

You can try use this code

 const downloadImg = document.getElementById('downImg') downloadImg.onclick = function() { const url = downloadImg.getAttribute('imgurl') const name = downloadImg.getAttribute('name') const link = document.createElement('a'); link.href = `data:application/octet-stream;base64,${encodeURIComponent(url)}`; link.download = name; document.body.appendChild(link); link.click(); document.body.removeChild(link); }
 <button id="downImg" imgurl="https://thesafety.us/images/articles/javascript-logo.png" name="javascript-logo.png">Download</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM