在javascript中下载图像时出现失败的网络错误



当我尝试在javascript中点击按钮下载图像时,我得到了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>

您可以尝试使用此代码

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>

最新更新