Przeglądaj źródła

优化文件下载功能

cc12458 1 rok temu
rodzic
commit
587116b1db
2 zmienionych plików z 29 dodań i 5 usunięć
  1. 11 5
      src/utils/request.js
  2. 18 0
      src/utils/zipdownload.js

+ 11 - 5
src/utils/request.js

@@ -52,12 +52,18 @@ service.interceptors.request.use(config => {
 })
 
 // 响应拦截器
-service.interceptors.response.use(res => {
-    if (res.config.fileType && res.data instanceof Blob) {
+service.interceptors.response.use(async res => {
+    if (res.data instanceof Blob) {
       const value = res.headers['Content-Disposition'] || res.headers['content-disposition'] || '';
-      return {
-        name: (value.match(/fileName=["']([^"']+)["']/) || [])[1],
-        blob: new Blob([res.data], { type: res.config.fileType }),
+      const type = res.headers['Content-Type'] || res.headers['content-type'] || res.config.fileType;
+      if (type === 'application/json') {
+        const text = await res.data.text()
+        res.data = JSON.parse(text);
+      } else {
+        return {
+          name: decodeURIComponent((value.match(/fileName=["']([^"']+)["']/i) || [])[1] || ''),
+          blob: new Blob([res.data], { type }),
+        }
       }
     } else if (res.config.forced) {
       return res;

+ 18 - 0
src/utils/zipdownload.js

@@ -40,3 +40,21 @@ export function resolveBlob(res, mimeType) {
   URL.revokeObjectURL(aLink.href);//清除引用
   document.body.removeChild(aLink);
 }
+
+export function downloadBlob({blob, name}) {
+  const link = document.createElement('a');
+  document.body.appendChild(link);
+
+  const url = URL.createObjectURL(blob);
+  link.href = url;
+  link.download = name;
+  link.click();
+
+  return new Promise(resolve => {
+    setTimeout(() => {
+      document.body.removeChild(link);
+      URL.revokeObjectURL(url);
+      resolve();
+    }, 20)
+  })
+}