Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

为什么图片无法跨域下载却可以右键另存为

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...
会出现跨域错误,

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...