downloadUtil.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { Message } from "element-ui";
  2. export default {
  3. // 通用文件下载方法
  4. async fileDownload(url, fileName) {
  5. try {
  6. // 检查URL是否合法
  7. if (!url) {
  8. Message.error("下载地址不能为空");
  9. return false;
  10. }
  11. // 检查文件类型
  12. const fileType = url
  13. .toLowerCase()
  14. .split(".")
  15. .pop();
  16. if (!["jpg", "jpeg", "png", "gif", "webp",'map4','mov','mp3'].includes(fileType)) {
  17. Message.error("该文件的格式不支持下载");
  18. return false;
  19. }
  20. const response = await fetch(url, {
  21. method: "GET",
  22. credentials: "include" // 包含 cookies
  23. });
  24. if (!response.ok) {
  25. Message.error("下载失败");
  26. return false;
  27. }
  28. const blob = await response.blob();
  29. const $link = document.createElement("a");
  30. $link.href = URL.createObjectURL(blob);
  31. $link.download = fileName || url.split("/").pop() || "download";
  32. document.body.appendChild($link);
  33. $link.click();
  34. document.body.removeChild($link);
  35. URL.revokeObjectURL($link.href);
  36. return true;
  37. } catch (error) {
  38. Message.error(error);
  39. return false;
  40. }
  41. }
  42. };