downLoad.ts 791 B

123456789101112131415161718192021222324
  1. import axios from "axios";
  2. const downService = axios.create({
  3. baseURL: import.meta.env.VITE_APP_UPLOAD_URL,
  4. });
  5. async function downloadFile(url: string, fileName: string) {
  6. try {
  7. const response = await downService.get(url, {
  8. responseType: "blob",
  9. });
  10. const blob = new Blob([response.data]);
  11. const link = document.createElement("a");
  12. const resurl = url;
  13. link.href = window.URL.createObjectURL(blob);
  14. const lastDotIndex = resurl.lastIndexOf(".");
  15. link.download = fileName + "." + resurl.substring(lastDotIndex + 1);
  16. document.body.appendChild(link);
  17. link.click();
  18. window.URL.revokeObjectURL(link.href);
  19. document.body.removeChild(link);
  20. } catch (error) {
  21. console.error("文件下载失败:", error);
  22. }
  23. }
  24. export { downloadFile };