63 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			JavaScript
		
	
	
			
		
		
	
	
			63 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			JavaScript
		
	
	
import { message, Modal } from "antd";
 | 
						|
import { useState } from "react";
 | 
						|
import { getFileName, getFileSuffix, getFileUrl } from "../../utils";
 | 
						|
 | 
						|
/**
 | 
						|
 * 下载文件
 | 
						|
 */
 | 
						|
export default function useDownloadFile(returnType = "object") {
 | 
						|
  // loading状态
 | 
						|
  const [loading, setLoading] = useState(false);
 | 
						|
 | 
						|
  // 下载文件
 | 
						|
  const downloadFile = (options) => {
 | 
						|
    setLoading(true);
 | 
						|
 | 
						|
    const { url, name: fileName } = options;
 | 
						|
    if (!url)
 | 
						|
      throw new Error("请传入 url");
 | 
						|
 | 
						|
    Modal.confirm({
 | 
						|
      title: "提示",
 | 
						|
      content: "确定要下载此文件吗?",
 | 
						|
      onOk: () => {
 | 
						|
        const fileUrl = getFileUrl();
 | 
						|
        let name = fileName;
 | 
						|
 | 
						|
        if (name) {
 | 
						|
          if (!getFileSuffix(name) && 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 urlObject = window.URL.createObjectURL(blob);
 | 
						|
            a.href = urlObject;
 | 
						|
            a.download = `${name}`;
 | 
						|
            a.click();
 | 
						|
            document.body.removeChild(a);
 | 
						|
            window.URL.revokeObjectURL(urlObject);
 | 
						|
          })
 | 
						|
          .catch(() => {
 | 
						|
            message.error("下载失败");
 | 
						|
          })
 | 
						|
          .finally(() => {
 | 
						|
            setLoading(false);
 | 
						|
          });
 | 
						|
      },
 | 
						|
    });
 | 
						|
  };
 | 
						|
 | 
						|
  if (returnType === "array")
 | 
						|
    return [loading, downloadFile];
 | 
						|
  return { loading, downloadFile };
 | 
						|
}
 |