import { attachUrlProtocol, getBasename } from './file'; import { isImage } from './is-image'; /** * 下载图片 */ export const downloadImg = (url: string, _fileName?: string) => { const fileName = _fileName || getBasename(url); const image = new Image(); image.setAttribute('crossOrigin', 'Anonymous'); image.onload = function () { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = image.width; canvas.height = image.height; context?.drawImage(image, 0, 0, image.width, image.height); const canvasUrl = canvas.toDataURL('images/png'); const a = document.createElement('a'); a.download = fileName; a.href = canvasUrl; a.click(); }; const tempUrl = new URL(attachUrlProtocol(url)); if (tempUrl.search) { image.src = `${url}&v=${Date.now()}`; } else { image.src = `${url}?v=${Date.now()}`; } }; /** * 通用下载 */ export const commonDownload = (fileUrl: string, _fileName?: string) => { const fileName = _fileName || getBasename(fileUrl); const a = document.createElement('a'); a.target = '_blank'; a.href = fileUrl; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); }; /** * 下载文件 * @param fileUrl 下载的文件路径 * @param fileName 重命名下载文件 */ export const downloadFile = (fileUrl: string, fileName?: string) => { // 防护代码 if (!fileUrl) return; fileName = fileName || ''; if (isImage(fileUrl) || isImage(fileName)) { downloadImg(fileUrl, fileName); } else { commonDownload(fileUrl, fileName); } };