download.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * 使用a链接下载文件,使用promise封装
  3. */
  4. export function downloadFileByA(url: string, name: string) {
  5. return new Promise((resolve, reject) => {
  6. try {
  7. const link = document.createElement('a')
  8. link.href = url
  9. link.download = name
  10. document.body.appendChild(link)
  11. link.click()
  12. document.body.removeChild(link)
  13. resolve(true)
  14. }
  15. catch (error) {
  16. reject(error)
  17. }
  18. })
  19. }
  20. /**
  21. * 下载文件
  22. * @returns
  23. */
  24. export async function downloadFile(url: string, name: string) {
  25. try {
  26. const response = await fetch(url)
  27. if (!response.ok)
  28. throw new Error('下载失败')
  29. const blob = await response.blob()
  30. const link = document.createElement('a')
  31. link.href = URL.createObjectURL(blob)
  32. link.download = name
  33. document.body.appendChild(link)
  34. link.click()
  35. document.body.removeChild(link)
  36. }
  37. catch (error) {
  38. console.error(error)
  39. }
  40. }
  41. /**
  42. * 下载文件
  43. * @returns
  44. */
  45. export async function downloadFileA(url: string, name: string) {
  46. try {
  47. const link = document.createElement('a')
  48. link.href = url
  49. link.download = name
  50. document.body.appendChild(link)
  51. link.click()
  52. document.body.removeChild(link)
  53. }
  54. catch (error) {
  55. console.log(error)
  56. }
  57. }