下载文件到本地
封装函数直接可用
/**
* @param href 文件内容blob
* @param name 文件名
*/
function downloadImg(href: string, name: string) {
const eleLink = document.createElement('a')
eleLink.download = name
eleLink.href = href
eleLink.click()
eleLink.remove()
}
/**
* 可直接下载 图片 pdf docx excel 等
* @param url 文件地址 例如 https://profile-avatar.csdnimg.cn/bajiutao.jpg
* @param name 文件名
*/
export function download(url: string, name: string) {
// 下载图片和文件
const photo = ['jpg', 'jpeg', 'png']
// const file = ['word', 'excel', 'pdf']
const fileType = url.split('.')[url.split('.').length - 1]
console.log(fileType, 'fileType')
if (photo.includes(fileType)) {
// 图片
const image = new Image()
image.setAttribute('crossOrigin', 'anonymous')
image.src = url
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height)
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob as Blob)
downloadImg(url, name)
// 用完释放URL对象
URL.revokeObjectURL(url)
})
}
}
else {
// 文件
window.open(url)
}
}