2025-10-22 14:43:42 +08:00
|
|
|
import { message, Modal } from "antd";
|
|
|
|
|
import { getFileName, getFileSuffix, getFileUrl } from "../../utils/index.js";
|
2025-10-31 14:26:46 +08:00
|
|
|
import { useState } from "react";
|
2025-10-22 14:43:42 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 下载文件
|
|
|
|
|
*/
|
2025-10-31 14:26:46 +08:00
|
|
|
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 };
|
2025-10-22 14:43:42 +08:00
|
|
|
}
|