Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

function?downloadImage(src)?{
??const?a?=?document.createElement('a')
??const?urlArr?=?src.split('/')
??const?name?=?urlArr[urlArr.length?-?1]
??a.download?=?name
??a.style.display?=?'none'
??const?image?=?new?Image()
??image.crossOrigin?=?"Anonymous"
??image.src?=?src?+?'?v='?+?Math.random()
??image.onload?=?()?=>?{
????const?base64?=?getBase64Image(image)
????a.href?=?base64
????document.body.appendChild(a)
????a.click()
????document.body.removeChild(a)
??}
??const?getBase64Image?=?(img)?=>?{
????const?canvas?=?document.createElement("canvas");
????canvas.width?=?img.width;
????canvas.height?=?img.height;
????const?ctx?=?canvas.getContext("2d");
????ctx.drawImage(img,?0,?0,?img.width,?img.height);
????const?ext?=?img.src.substring(img.src.lastIndexOf(".")?+?1).toLowerCase();
????const?dataURL?=?canvas.toDataURL("image/"?+?ext);
????return?dataURL;
??}
}

通过以上方式下载https://img.3dmgame.com/uploa...
会出现跨域错误,

为什么图片可以另存为呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

因为你直接点连接,相当于单独窗口打开,服务器端可能有防盗链处理判断,这种相当于盗链而被拒绝。
另存为是在当前浏览下,已经下载数据的保存,不会触发这样的机制。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...