当前位置: 首页 > Web前端 > HTML5

JS通过url下载图片

时间:2023-04-05 19:01:18 HTML5

如果你从api得到一张图片的url,你可以很方便的使用标签显示在页面上,但是你不需要显示,而是下载,怎么办?下面给出三种解决方案:使用fetch:exportconstdownloadImage=(imageUrl:string,name:string):void=>{fetch(imageUrl,{method:'get',mode:'cors',}).then((response)=>response.blob()).then((data)=>{constdownloadUrl=window.URL.createObjectURL(newBlob([data]));constlink=document.createElement('a');链接.href=downloadUrl;link.setAttribute('download',name);document.body.appendChild(link);link.click();link.remove();});};使用axios:exportconstdownloadImage=(imageUrl:string,name:string):void=>{axios.get(imageUrl,{responseType:'blob'}).then((res)=>{constdownloadUrl=window.URL.createObjectURL(newBlob([res.data]));constlink=document.createElement('a');link.href=downloadUrl;link.setAttribute('download',name);document.body.appendChild(link);link.click();l墨水.删除();});};使用canvas:exportconstdownloadImage=(imageUrl:string,name:string):void=>{constimage=newImage();image.setAttribute('crossOrigin','anonymous');image.onload=function():void{console.log(image);constcanvas=document.createElement('canvas');canvas.width=image.width;canvas.height=image.height;constcontext=canvas.getContext('2d')asCanvasRenderingContext2D;context.drawImage(image,0,0,image.width,image.height);consturl=canvas.toDataURL('image/png');consta=document.createElement('a');constevent=newMouseEvent('点击');a.下载=名称;a.href=网址;a.dispatchEvent(事件);};image.src=imageUrl;};