downLoad.ts 858 B

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