/** * 下载图片(本地地址) * @param href 图片地址 * @param name 图片名称 */ function downloadImg(href: string, name: string) { console.log(href, 'href') const eleLink = document.createElement('a') eleLink.download = name eleLink.href = href eleLink.click() eleLink.remove() } /** * 下载文件 * @param url 文件地址 * @param name 文件名 */ export function download(url: string, name: string) { // 下载图片和文件 const photo = ['jpg', 'jpeg', 'png'] // const file = ['doc', '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 as CanvasRenderingContext2D).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) } }