123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import { Message } from "element-ui";
- export default {
- // 通用文件下载方法
- async fileDownload(url, fileName) {
- try {
- // 检查URL是否合法
- if (!url) {
- Message.error("下载地址不能为空");
- return false;
- }
- // 检查文件类型
- const fileType = url
- .toLowerCase()
- .split(".")
- .pop();
- if (!["jpg", "jpeg", "png", "gif", "webp",'map4','mov','mp3'].includes(fileType)) {
- Message.error("该文件的格式不支持下载");
- return false;
- }
- const response = await fetch(url, {
- method: "GET",
- credentials: "include" // 包含 cookies
- });
- if (!response.ok) {
- Message.error("下载失败");
- return false;
- }
- const blob = await response.blob();
- const $link = document.createElement("a");
- $link.href = URL.createObjectURL(blob);
- $link.download = fileName || url.split("/").pop() || "download";
- document.body.appendChild($link);
- $link.click();
- document.body.removeChild($link);
- URL.revokeObjectURL($link.href);
- return true;
- } catch (error) {
- Message.error(error);
- return false;
- }
- }
- };
|