js跨域下载图片

有一个常见的需求,就是下载图片。
以以往的经验,使用了a标签的方式进行了下载。如下

<button @click="downloadPic">下载</button>
donloadPic () {
    
    
	let url = 'http://a.b.com/test.png'
	let a = document.createElement('a')
	a.src = url
	a.download = 'download.' + url.slice(url.lastIndexOf('.')+1)
	a.click()
}

但是上述方法只能在图片与我们的地址同域的情况下有作用,当出现跨域的情况时,download的属性便会失效,导致当我们进行上述操作后网站会跳转到图片地址上,而不是进行下载。
为此,在进行网上的资料查询后找到了以下的解决方法。
方法一(通过图片的base64编码数据进行下载):

downloadPic () {
    
    
	let imgsrc= 'http://a.b.com/test.png'
	var image = new Image()
	// 解决跨域canvas污染问题
	image.setAttribute('crossOrigin''anonymous')
	image.onload = function () {
    
    
		let canvas = document.createElement('canvas')
		canvas.width = image.width
		canvas.height = image.height
		let context = canvas.getContext('2d')
		context.drawImage(image, 0, 0, image.width, image.height)
		let url = canvas.toDateURL('image/png') // 得到图片的base64编码数据
		let a = document.createElement('a')
		a.download = 'download' + url.slice(url.lastIndexOf('.'))
		a.href = url
		a.click()
	}
	image.src = imgsrc
}

上述代码中需要注意的是在获取图片的base64编码数据的时候,图片越大,转换后的base64编码就越长,应避免对大图的编码转换,防止超出浏览器的访问路径长度限制。

方法二(利用XMLHttpRequest,blob):

downloadPic () {
    
    
	let imgsrc= 'http://a.b.com/test.png'
	let x = new XMLHttpRequest()
	x.open('GET', url, true)
	x.responseType = 'blob'
	x.onload = function () {
    
    
		let url = window.URL.createObjectURL(x.response)
		let a = document.createElement('a')
		a.href = url
		a.download = 'download';
		a.click()
	}
	x.send()
}

值得注意的是,在方法二中a.download属性并没有赋予后缀,但是在下载的时候却会为我们添加上图片的后缀路径,在方法一中则不会自动添加。

对于方法二中的x.responseTyoe = 'blob’因为我也说不清这个属性的作用,所以不在此处解释,后续了解清楚后会再说明。

猜你喜欢

转载自blog.csdn.net/m0_38038767/article/details/110946165