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

Categories

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

图片能加载却不能是为什么?

需求背景是这样的,图片批量下载,但由于都是外链,就要跨域用canvas绘出来再下载,然后问题是,有两种外链,一种是http://image/123.jpg,这种可以请求下来并成功下载;但是另一种是http://image/123.jpg?accessKe...,这种就各种报错了。

相关代码如下:

            var canvas = document.createElement('canvas');
            var img = document.createElement('img');
            img.setAttribute("crossOrigin",'Anonymous');
            var timestamp = Date.parse(new Date());
            img.src = item.url.indexOf('?') > -1 ? item.url+'&v='+timestamp:item.url+'?v='+timestamp;
            img.onload = function(e) {
                canvas.width = img.width;
                canvas.height = img.height;
                var context = canvas.getContext('2d');
                context.drawImage(img, 0, 0, img.width, img.height);
                canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
                
                canvas.toBlob((blob)=>{
                 let link = document.createElement('a');
                 link.href = window.URL.createObjectURL(blob);
                 link.download = item.name+timestamp;
                 link.click();
                }, "image/jpeg");
            }

报错信息如下:
image.png

我的问题是:无法下载的这部分外链,是否是因为验证信息造成的?如果不是,那是什么原因?如果是,为什么这种图片能打开查看但却不能请求下来用呢?


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

1 Answer

0 votes
by (71.8m points)

跨域了.
简单的解决办法是让后端增加一个接口,用于代理图片
/api/proxyimage?url=.该接口接受一个图片链接,再流式返回图片数据即可.
前端在图片链接前面拼上接口即可.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...