37 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			JavaScript
		
	
	
			
		
		
	
	
			37 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			JavaScript
		
	
	
| import { message, Modal } from "antd";
 | |
| import { getFileName, getFileSuffix, getFileUrl } from "../../utils/index.js";
 | |
| 
 | |
| /**
 | |
|  * 下载文件
 | |
|  */
 | |
| export default function useDownloadFile(url, name) {
 | |
|   if (!url)
 | |
|     throw new Error("没有下载地址");
 | |
|   Modal.confirm({ title: "提示", content: "确定要下载此文件吗?", onOk: () => {
 | |
|     const fileUrl = getFileUrl();
 | |
|     if (name) {
 | |
|       if (!getFileSuffix(url))
 | |
|         name = name + getFileSuffix(url);
 | |
|     }
 | |
|     else {
 | |
|       name = getFileName(url);
 | |
|     }
 | |
|     fetch(!url.includes(fileUrl) ? fileUrl + url : url)
 | |
|       .then(res => res.blob())
 | |
|       .then((blob) => {
 | |
|         const a = document.createElement("a");
 | |
|         document.body.appendChild(a);
 | |
|         a.style.display = "none";
 | |
|         const url = window.URL.createObjectURL(blob);
 | |
|         a.href = url;
 | |
|         a.download = `${name}`;
 | |
|         a.click();
 | |
|         document.body.removeChild(a);
 | |
|         window.URL.revokeObjectURL(url);
 | |
|       })
 | |
|       .catch(() => {
 | |
|         message.error("下载失败");
 | |
|       });
 | |
|   } });
 | |
| }
 |