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; }