Prechádzať zdrojové kódy

chore(utils): 优化接口请求函数,支持下载文件

wangcong 3 mesiacov pred
rodič
commit
727f7f9eb5
2 zmenil súbory, kde vykonal 39 pridanie a 2 odobranie
  1. 18 2
      src/constants/index.ts
  2. 21 0
      src/utils/index.ts

+ 18 - 2
src/constants/index.ts

@@ -10,8 +10,8 @@ export const enum LanguageType {
  * 协议类型
  */
 export const enum ProtocolType {
-  ModbusRTU,
-  S7,
+  ModbusRTU = 'ModbusRTU',
+  S7 = 'S7',
 }
 
 /**
@@ -21,3 +21,19 @@ export const enum ProtocolConfigMethod {
   ImportFromTemplate,
   ManuallyCreate,
 }
+
+/**
+ * 字典编码
+ */
+export const enum DictCode {
+  AllProtocolType = 'all_protocol_type',
+  ModbusProtocolType = 'modbus_protocol_type',
+  S7ProtocolType = 's7_protocol_type',
+  ProtocolTemplateFileName = 'protocol_template_file_name',
+}
+
+/**
+ * 符合文件格式的内容类型(接口请求响应)
+ */
+export const fileContentTypeRegExp =
+  /^(application\/(octet-stream|pdf|zip|x-tar|msword|vnd.openxmlformats-officedocument\.wordprocessingml\.document|vnd.ms-excel|vnd.openxmlformats-officedocument\.spreadsheetml\.sheet)|image\/|audio\/|video\/)/;

+ 21 - 0
src/utils/index.ts

@@ -1,6 +1,7 @@
 import { kebabCase } from 'lodash-es';
 
 import { t } from '@/i18n';
+import { fileContentTypeRegExp } from '@/constants';
 
 import { fetchWithTimeout } from './fetch';
 
@@ -57,6 +58,12 @@ export const request = async <T>(url: string, init: RequestInit = {}, timeout?:
   //     saveToken(token);
   //   }
   // }
+  const contentType = res.headers.get('content-type');
+  const isBlob = fileContentTypeRegExp.test(contentType || '');
+
+  if (isBlob) {
+    return (await res.blob()) as T;
+  }
 
   const json: ApiResponse<T> = await res.json();
   const { data, code, msg } = json;
@@ -92,3 +99,17 @@ export const generateThemeCSSVar = (token: GlobalToken, prefix: string): string
 export const addUnit = (val: number, unit: string = 'px'): string => {
   return val + unit;
 };
+
+export const downloadBlob = (blob: Blob, name: string) => {
+  const url = window.URL.createObjectURL(blob);
+  const a = document.createElement('a');
+
+  a.href = url;
+  a.download = name;
+
+  document.body.appendChild(a);
+  a.click();
+
+  document.body.removeChild(a);
+  window.URL.revokeObjectURL(url);
+};