zy-vue-library/hooks/useDownloadFile/index.js

33 lines
1.2 KiB
JavaScript

import { ElMessage, ElMessageBox } from "element-plus";
import { getFileName, getFileSuffix, getFileUrl } from "../../utils/index.js";
/**
* @param {string} url - 文件的下载地址 URL
* @param {string} [name] - 可选的文件名,不带后缀。若未提供,则从 URL 中提取文件名
* @returns {Promise<void>} 无返回值,但会触发浏览器下载行为
*/
export default async function useDownloadFile(url, name) {
if (!url) throw new Error("没有下载地址");
await ElMessageBox.confirm("确定要下载此文件吗?", { type: "warning" });
const FILE_URL = getFileUrl();
if (name) {
if (!getFileSuffix(url)) name = name + getFileSuffix(url);
} else name = getFileName(url);
fetch(url.indexOf(FILE_URL) === -1 ? FILE_URL + 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(() => {
ElMessage.error("下载失败");
});
}