使用前端js下载远程跨域的网络图片
介绍
用js下载同源服务器或者本地图片时可以用a标签加上download属性然后通过点击下载,但是当a标签的href属性是跨域的网络图片地址时,点击链接会直接打开图片,并不会自动下载,所以首先要想办法把远程的网络图片转成base64或者blob对象,然后就再通过a链接点击下载。
实现方式
第一种方法用xhr请求网络图片返回blob对象
第一种方式是用fileReader文件读取的方式,读取blob对象为base64
let img_src = 'https://img0.baidu.com/it/u=17550577,892256196&fm=253&app=138&size=w931&n=0&f=PNG&fmt=auto?sec=1666285200&t=5565742deae20ef3797e159134b79864'
let xhr = new XMLHttpRequest()
xhr.open('get',img_src,true)
xhr.responseType = 'blob'
xhr.send()
xhr.onload = function(res) {
let fileReader = new FileReader()
fileReader.readAsDataURL(res.target.response)
fileReader.onload = function (tem) {
console.log(tem)
let a = document.createElement('a')
a.href = tem.target.result
a.download = '网络图片下载'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
}
第二种方式用url的createObjectURL方法,把blob对象转成一个临时的本地url地址
let img_src = 'https://img0.baidu.com/it/u=17550577,892256196&fm=253&app=138&size=w931&n=0&f=PNG&fmt=auto?sec=1666285200&t=5565742deae20ef3797e159134b79864'
let xhr = new XMLHttpRequest()
xhr.open('get',img_src,true)
xhr.responseType = 'blob'
xhr.send()
xhr.onload = function(res) {
let img = document.querySelector('.img')
let blob = window.URL.createObjectURL(res.target.response)
img.src = blob
img.onload = function() {
window.URL.revokeObjectURL(res.target.response)
}
let a = document.createElement('a')
a.download = 'blob下载'
a.href = blob
document.body.append(a)
a.click()
document.body.remove(a)
}
第二种方法用canvas的toDataURL方法转成base64
let img = new Image()
img.src = img_src
img.crossOrigin = ''
img.onload = function() {
let canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
let ctx = canvas.getContext('2d')
ctx.drawImage(img,0,0,canvas.width,canvas.height)
const base64Url = canvas.toDataURL('image/jpeg')
console.log(base64Url)
let a = document.createElement('a')
a.href = base64Url
a.download = 'canvas_download'
document.body.append(a)
a.click()
document.body.remove(a)
}
浙公网安备 33010602011771号