一、下载非同源图片
onDownloadImg() {
fetch('https://qiniu.cn/example-01.jpg')
.then(response => response.blob())
.then(blob => {
const blobUrl = URL.createObjectURL(blob)
const ele = document.createElement('a')
ele.href = blobUrl
ele.download = 'example.jpg' // 下载的文件名
document.body.appendChild(ele)
ele.click()
URL.revokeObjectURL(blobUrl) // 释放URL对象
document.body.removeChild(ele) // 下载完成后移除 <a> 元素
})
.catch(error => console.error('Error downloading image:', error))
}
二、下载非同源PDF文件
onDownloadPdf() {
fetch('https://qiniu.cn/example.pdf', {
method: 'GET',
headers: {
'Content-Type': 'application/pdf'
}
})
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(new Blob([blob]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'example.pdf')
document.body.appendChild(link)
link.click()
})
.catch(error => console.log(error))
}