巴青农资商城

image.js 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { joinFileUrl, API_HOST } from '@/config'
  2. const PLACEHOLDER_PATHS = ['/static/logo.png']
  3. /** 是否外链或 data URL */
  4. export function isExternalUrl(url) {
  5. if (!url) return false
  6. return /^(https?:|data:|\/\/)/i.test(String(url).trim())
  7. }
  8. /** 去掉 /dev-api 等代理前缀,得到后端真实路径 */
  9. function stripApiProxyPrefix(path) {
  10. return String(path).replace(/^\/(dev-api|prod-api|shop-api)/, '') || '/'
  11. }
  12. function isPlaceholderPath(path) {
  13. const raw = String(path || '').trim()
  14. return PLACEHOLDER_PATHS.includes(raw)
  15. }
  16. /**
  17. * 是否已是可直接使用的图片地址(避免重复拼接)
  18. */
  19. export function isResolvedFileUrl(url) {
  20. if (!url) return false
  21. const raw = String(url).trim()
  22. if (isExternalUrl(raw)) return true
  23. if (raw.startsWith('/static/')) return true
  24. const apiHost = String(API_HOST).replace(/\/$/, '')
  25. return !!(apiHost && (raw === apiHost || raw.startsWith(`${apiHost}/`)))
  26. }
  27. /**
  28. * 将后端返回的图片路径转为可展示的完整 URL(可重复调用)
  29. * 结果形如:http://192.168.1.6:8020/profile/upload/xxx.jpg
  30. * @param {string} path bannerImage / categoryPic / mainPic 等
  31. */
  32. export function resolveFileUrl(path) {
  33. if (path == null || path === '') {
  34. return ''
  35. }
  36. let raw = String(path).split(',')[0].trim()
  37. if (!raw || isPlaceholderPath(raw)) {
  38. return ''
  39. }
  40. if (isExternalUrl(raw)) {
  41. return raw
  42. }
  43. if (raw.startsWith('/static/')) {
  44. return raw
  45. }
  46. const apiHost = String(API_HOST).replace(/\/$/, '')
  47. if (apiHost && (raw === apiHost || raw.startsWith(`${apiHost}/`))) {
  48. return raw
  49. }
  50. if (/^\/(dev-api|prod-api|shop-api)\//i.test(raw)) {
  51. raw = stripApiProxyPrefix(raw)
  52. }
  53. const normalized = raw.startsWith('/') ? raw : `/${raw}`
  54. return joinFileUrl(normalized)
  55. }
  56. /**
  57. * 将逗号分隔或数组形式的图片路径转为完整 URL 列表
  58. * @param {string|string[]|null|undefined} pathOrList
  59. */
  60. export function resolveFileUrlList(pathOrList) {
  61. if (pathOrList == null || pathOrList === '') return []
  62. if (Array.isArray(pathOrList)) {
  63. return pathOrList.map((item) => resolveFileUrl(item)).filter(Boolean)
  64. }
  65. return String(pathOrList)
  66. .split(',')
  67. .map((s) => resolveFileUrl(s.trim()))
  68. .filter(Boolean)
  69. }