gerson
2024-06-30 5010f52d22cf34660a338611fbb679d422901faa
src/utils/util.ts
@@ -11,6 +11,42 @@
import axios from 'axios';
import { MAIN_URL } from '../constants';
/**
 * 普通对象转为 formData
 * @param obj
 */
export const toFormData = (obj: any) => {
   const formData = new FormData();
   const addFormData = (subObj, prePrefix = '', isArray = false) => {
      for (const key in subObj) {
         if (Object.prototype.hasOwnProperty.call(subObj, key)) {
            const value = subObj[key];
            let currentKey = '';
            if (prePrefix === '') {
               currentKey = key;
            } else if (isArray) {
               currentKey = `${prePrefix}[${key}]`;
            } else {
               currentKey = `${prePrefix}.${key}`;
            }
            if (value != null && Array.isArray(value) && value.length > 0) {
               addFormData(value, currentKey, true);
            } else if (value != null && typeof value === 'object' && Object.values(value).length > 0) {
               addFormData(value, currentKey, false);
            } else {
               formData.append(currentKey, value);
            }
         }
      }
   };
   addFormData(obj);
   return formData;
};
/**
 * @description 当碰到 JSON 中存在过长的数字时,使用 JSONbigString 解析,数字会转为字符串处理
 * 用法:JSONbigString.parse(jsonStr))