js cross-domain downloading pictures

A common requirement is to download pictures.
Based on past experience, the a tag was used for downloading. as follows

<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()
}

However, the above method can only work when the image is in the same domain as our address. When there is a cross-domain situation, the download attribute will be invalid, causing the website to jump to the image address after we perform the above operations. Instead of downloading.
For this reason, the following solutions were found after conducting online information inquiries.
Method one (download through base64 encoded data of the picture):

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
}

The above code should be noted that when obtaining the base64 encoded data of the picture, the larger the picture, the longer the converted base64 encoding. The encoding conversion of the large picture should be avoided to prevent the access path length limit of the browser from exceeding.

Method two (using 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()
}

It is worth noting that the a.download attribute is not given a suffix in the second method, but the suffix path of the picture will be added for us when downloading, and it will not be automatically added in the first method.

For the x.responseTyoe ='blob' in the second method, because I can't explain the function of this attribute, I won't explain it here, and I will explain it later when I understand it clearly.

Guess you like

Origin blog.csdn.net/m0_38038767/article/details/110946165