utils.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { httpApp } from "@/plugins/axiosApp";
  2. import router from "@/router";
  3. import { AxiosResponse } from "axios";
  4. // 下载文件
  5. export async function downloadFileURL(url: string, name?: string) {
  6. return httpApp
  7. .get(url, { responseType: "blob" })
  8. .then((res) => {
  9. return responseToFile(res);
  10. })
  11. .catch((err) => {});
  12. }
  13. export async function responseToFile(response: AxiosResponse) {
  14. return new Promise((resolve) => {
  15. const { data, headers } = response;
  16. const fileName = headers["content-disposition"].replace(
  17. /\w+;\s*filename=(.*)/,
  18. "$1"
  19. );
  20. //Here, when the JSON file is returned, the JSON.stringify Processing, other types of files do not need to be processed
  21. //const blob = new Blob([JSON.stringify(data)], ...)
  22. const blob = new Blob([data], { type: headers["content-type"] });
  23. let dom = document.createElement("a");
  24. let url = window.URL.createObjectURL(blob);
  25. dom.href = url;
  26. dom.download = decodeURI(fileName);
  27. dom.style.display = "none";
  28. document.body.appendChild(dom);
  29. dom.click();
  30. dom.parentNode?.removeChild(dom);
  31. window.URL.revokeObjectURL(url);
  32. });
  33. }
  34. // 返回
  35. export function goBack() {
  36. router.back();
  37. }