Browse Source

更新 'src/services/net.service.ts'

Caner 2 years ago
parent
commit
526c11c714
1 changed files with 30 additions and 0 deletions
  1. 30 0
      src/services/net.service.ts

+ 30 - 0
src/services/net.service.ts

@@ -47,6 +47,36 @@ export default class NetService extends Service {
     return this.fetch(url, { method: 'PUT', body: JSON.stringify(params) }, timeout)
   }
 
+  /**
+   * 下载文件
+   * @param url url|blob
+   * @param fileName
+   */
+  downloadFile(url: string | Blob, fileName: string) {
+    const download = (blob: Blob, fileName: string) => {
+      const a = document.createElement('a')
+      document.body.appendChild(a)
+      a.style.display = 'none'
+      // 使用获取到的blob对象创建的url
+      const url = window.URL.createObjectURL(blob)
+      a.href = url
+      // 指定下载的文件名
+      a.download = fileName
+      a.click()
+      document.body.removeChild(a)
+      // 移除blob对象的url
+      window.URL.revokeObjectURL(url)
+    }
+    return new Promise<void>((resolve, reject) => {
+      if (url instanceof Blob) {
+        download(url, fileName)
+        resolve()
+      } else {
+        fetch(url).then((res) => res.blob()).then((blob) => download(blob, fileName)).finally(() => resolve())
+      }
+    })
+  }  
+  
   /** token 续期 */
   async refresh(token: string) {
     this.post('', { token }).then((res) => {