Files

35 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2026-08-31 11:33:59 +08:00
import config from '@/config/index.js'
import { uploadFile } from '@/utils/request.js'
const getBackendOrigin = () => config.apiBaseURL.replace(/\/api\/?$/, '')
/**
* 将后端返回的图片地址转换为当前 APP 可访问的地址。
* 本地存储配置可能生成 127.0.0.1,Android 真机访问时必须改用局域网后端地址。
*/
export function normalizeImageUrl(imageUrl) {
if (typeof imageUrl !== 'string' || !imageUrl) return imageUrl
if (/^data:image\//i.test(imageUrl) || /^file:\/\//i.test(imageUrl)) return imageUrl
if (/^https?:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?(?=\/|$)/i.test(imageUrl)) {
return imageUrl.replace(/^https?:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?/i, getBackendOrigin())
}
if (imageUrl.startsWith('//127.0.0.1') || imageUrl.startsWith('//localhost')) {
return imageUrl.replace(/^\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?/i, getBackendOrigin())
}
return imageUrl.startsWith('/') ? `${getBackendOrigin()}${imageUrl}` : imageUrl
}
/**
* 上传单张图片。页面只负责保存本地临时路径,提交时才调用本方法。
*/
export async function uploadImage(filePath, subDir = 'image') {
const result = await uploadFile('/file/image', filePath, {
sub_dir: subDir
}, {
baseURL: config.apiBaseURL
})
const imageUrl = result?.url || result?.full_url || result?.path
if (!imageUrl) throw new Error('图片上传未返回地址')
return normalizeImageUrl(imageUrl)
}