puzhibing
6 天以前 0db8c9b94a9ac655549d5eba5c2a6c92ac386c06
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import axios from 'axios';
import apiConfig from './baseurl';
 
export const customRequest = (params) => {
  const { file, onSuccess, onError } = params;
  uploadObs(file)
    .then((ret) => {
      onSuccess(ret);
    })
    .catch((ret) => {
      onError();
    });
};
 
export const customUploadRequest = ({ file, onSuccess, onError, action, headers }) => {
  // 默认 action 为 apiConfig.imgUrl
  const uploadUrl = action || apiConfig.imgUrl;
  // 默认 headers 带上 Authorization
  const uploadHeaders = {
    Authorization: sessionStorage.getItem('token') || '',
    ...headers
  };
  const formData = new FormData();
  formData.append('file', file);
 
  axios.post(uploadUrl, formData, { headers: uploadHeaders })
    .then(res => {
      try {
        onSuccess(res.data);
      } catch (e) {
        console.error('onSuccess error:', e);
      }
    })
    .catch(err => {
      try {
        onError(err, file);
      } catch (e) {
        console.error('onError error:', e);
      }
    });
};
 
export function getUploadedFilePath(response) {
  const payload = response && response.data && typeof response.data === 'object'
    ? response.data
    : response;
 
  if (typeof payload === 'string') return payload.trim();
  if (!payload || typeof payload !== 'object') return '';
 
  const nestedPath = payload.data && typeof payload.data === 'object'
    ? getUploadedFilePath(payload.data)
    : '';
  const candidates = [nestedPath, payload.data, payload.url, payload.fileUrl, payload.path, payload.msg];
  const successMessages = ['操作成功', '上传成功', 'success', 'ok'];
  return candidates.find(value => {
    return typeof value === 'string'
      && value.trim()
      && !successMessages.includes(value.trim().toLowerCase());
  }) || '';
}
 
export function normalizeFileList(value) {
  let files = value;
  if (typeof files === 'string') {
    const text = files.trim();
    if (!text) return [];
    try {
      files = JSON.parse(text);
    } catch (e) {
      files = [text];
    }
  }
  if (!Array.isArray(files)) files = files ? [files] : [];
 
  return files.map((file, index) => {
    const source = typeof file === 'string' ? { url: file } : (file || {});
    const url = source.url || source.fileUrl || source.path || source.filePath || '';
    const fallbackName = String(url).split(/[\\/]/).pop() || `附件${index + 1}`;
    return {
      ...source,
      name: source.name || source.fileName || fallbackName,
      url,
      uid: source.uid || source.id || `legacy-file-${index}-${url}`
    };
  }).filter(file => file.url);
}
 
export function getFullUrl(url) {
  if (!url) return "";
  const value = String(url).trim().replace(/\\/g, '/');
  if (/^(data|blob):/.test(value)) return value;
 
  const isAbsoluteUrl = /^(https?:)?\/\//.test(value);
  if (isAbsoluteUrl && !/^(https?:)?\/\/(localhost|127\.0\.0\.1)(:\d+)?\//i.test(value)) {
    return value;
  }
 
  const base = getAllocateIp().replace(/\/+$/, '') + '/';
  let path = value;
  if (isAbsoluteUrl) {
    const parsedUrl = new URL(value, window.location.origin);
    path = `${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;
  }
  path = path.replace(/^\/+/, '');
  if (/\/images\/$/.test(base) && path.startsWith('images/')) {
    path = path.slice('images/'.length);
  }
  return base + path;
}
/**
 * 通用文件下载方法
 * @param {string} url 文件的下载地址(支持相对和绝对路径)
 * @param {string} name 下载保存的文件名(可选)
 */
export function downloadFileByUrl(url, name) {
  if (!url) return;
  // 处理相对路径
  const fullUrl = getFullUrl(url);
  const a = document.createElement('a');
  a.href = fullUrl;
  if (name) {
    a.download = name;
  } else {
    a.download = '';
  }
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
 
/**
 * 在新标签页打开文件(预览或下载)
 * @param {string} url 文件地址(支持相对和绝对路径)
 */
export function openFileInNewTab(url) {
  if (!url) return;
  const fullUrl = getFullUrl(url);
  window.open(fullUrl, '_blank');
}
/**
 * 判断文件是否为图片
 * @param {string} url 文件URL
 * @returns {boolean} 是否为图片文件
 */
export function isImageFile(url) {
  if (!url) return false;
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
  const lowerUrl = url.toLowerCase();
  return imageExtensions.some(ext => lowerUrl.includes(ext));
}
 
export function getAllocateIp() {
  const userInfo = JSON.parse(sessionStorage.getItem("userInfo") || "{}");
  const allocateIp = String(userInfo.allocateIp || '').trim();
  const isLoopback = /^(localhost|127\.0\.0\.1)$/i.test(allocateIp);
  return allocateIp && !isLoopback
    ? `http://${allocateIp}:11223/images/`
    : apiConfig.showImgUrl;
}