kongdeqiang
2026-10-12 285bf234bd50ce54fcae7bb777f8fa579b91266e
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<template>
  <div class="authenticated-image">
    <n-spin v-if="loading" size="small" class="img-loading" />
    <div v-else-if="error" class="img-error" :title="error">
      <span class="img-error-icon">⚠</span>
      <span class="img-error-text">图片加载失败</span>
    </div>
    <img
      v-else-if="objectUrl"
      :src="objectUrl"
      class="message-image-thumb"
      :alt="alt"
      :title="title"
    />
  </div>
</template>
 
<script setup>
import { onBeforeUnmount, ref, watch } from 'vue'
import { NSpin } from 'naive-ui'
 
/**
 * 需要鉴权的图片。
 *
 * ## 为什么不能直接写 `<img src="/api/files/1/content">`
 *
 * 后端的文件内容接口需要 `Authorization: Bearer <jwt>`(否则人人知道 id
 * 就能下载别人的文件,是典型的 IDOR 漏洞)。但 `<img>` 标签发出的请求
 * **不会携带自定义请求头** —— 浏览器只按同源规则带上 Cookie。
 * 结果是后端返回 401,浏览器显示一个「图片损坏」的破图标,
 * 而 DOM 里 `<img>` 元素确实存在,用「元素数量」做断言根本发现不了。
 *
 * 正确做法:用 axios 带 token 取回二进制(responseType: 'blob'),
 * 再 `URL.createObjectURL` 转成本地可访问的地址交给 `<img>`。
 *
 * ## 缓存
 *
 * 模块级缓存按 fileId 复用 objectURL:
 *   - 同一条消息的缩略图与放大预览共用一份,不重复请求
 *   - 会话内滚动、切分支重渲染不会反复拉取
 * objectURL 会持有内存,因此这里**不在卸载时 revoke**(否则会打断
 * 其他地方对同一张图的显示),而是在页面整体卸载时统一释放。
 */
const props = defineProps({
  /** 图片在 upload_file 中的 id */
  fileId: { type: [Number, String], required: true },
  alt: { type: String, default: '图片' },
  title: { type: String, default: '' }
})
 
const emit = defineEmits(['loaded'])
 
const objectUrl = ref('')
const loading = ref(true)
const error = ref('')
 
/**
 * fileId -> objectURL 缓存。
 * value 为 'pending' 表示请求进行中,避免同一张图并发拉多次。
 */
const urlCache = new Map()
const pendingResolvers = new Map()
 
async function load() {
  const key = String(props.fileId)
  if (!key) return
 
  // 命中缓存
  const cached = urlCache.get(key)
  if (cached && cached !== 'pending') {
    objectUrl.value = cached
    loading.value = false
    emit('loaded', cached)
    return
  }
 
  // 已有同 id 的请求在飞:等它的结果,避免重复下载
  if (cached === 'pending') {
    const url = await new Promise((resolve) => {
      const list = pendingResolvers.get(key) || []
      list.push(resolve)
      pendingResolvers.set(key, list)
    })
    if (url) {
      objectUrl.value = url
      loading.value = false
      emit('loaded', url)
    }
    return
  }
 
  urlCache.set(key, 'pending')
  loading.value = true
  error.value = ''
 
  try {
    // 动态 import 避免与 axios 封装产生循环依赖
    const { default: http } = await import('@/api/axios')
    const blob = await http.get(`/files/${key}/content`, { responseType: 'blob' })
 
    // axios 在 responseType: 'blob' 时不会走我们封装的 Result 解包
    // (响应不是 {code,msg,data} 结构),这里拿到的是原始 Blob
    if (!(blob instanceof Blob)) {
      throw new Error('响应不是二进制数据')
    }
 
    const url = URL.createObjectURL(blob)
    urlCache.set(key, url)
    objectUrl.value = url
    emit('loaded', url)
  } catch (e) {
    urlCache.delete(key)
    error.value = e.message || '加载失败'
  } finally {
    loading.value = false
    // 唤醒等待中的组件
    const list = pendingResolvers.get(key) || []
    pendingResolvers.delete(key)
    list.forEach((resolve) => resolve(urlCache.get(key) || ''))
  }
}
 
watch(() => props.fileId, load, { immediate: true })
 
/**
 * 页面整体卸载时统一释放所有 objectURL。
 *
 * 只清一次即可:本组件被卸载时(例如切换会话)不释放,
 * 因为缓存是跨组件共享的;真正需要回收内存的时机是离开页面。
 */
function releaseAll() {
  for (const [key, url] of urlCache) {
    if (url && url !== 'pending') {
      URL.revokeObjectURL(url)
    }
  }
  urlCache.clear()
}
 
// 用 pagehide 而不是 beforeunload:前者在移动端与 bfcache 场景下更可靠
if (typeof window !== 'undefined') {
  window.addEventListener('pagehide', releaseAll)
}
 
onBeforeUnmount(() => {
  // 组件卸载时只解绑,不释放缓存(其他消息可能还在用同一张图)
})
</script>
 
<style scoped>
.authenticated-image {
  display: flex;
  align-items: center;
  justify-content: center;
  /*
   * 尺寸规则必须放在**本组件的 scoped 样式**里。
   *
   * 早前把 .message-image-thumb 的 max-width 写在 MessageItem.vue 的
   * scoped 样式里,但 <img> 已经被挪进本组件 —— 父组件的 scoped 属性
   * 不会作用到子组件内部元素,选择器匹配不上,于是图片按原始尺寸渲染
   * (整页截图能到 1200px 宽,把消息区撑爆)。
   *
   * 缩略图用一个克制的固定上限,点击后再看大图,
   * 避免长截图把对话流挤得没法读。
   */
  max-width: 220px;
  max-height: 220px;
}
 
.message-image-thumb {
  max-width: 100%;
  max-height: 100%;
  /* 保持比例缩放,不裁切也不拉伸 */
  object-fit: contain;
  border-radius: 8px;
  border: 1px solid var(--border-color);
  display: block;
}
 
.img-loading {
  width: 60px;
  height: 60px;
}
 
.img-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  width: 120px;
  height: 80px;
  border: 1px dashed #d1d5db;
  border-radius: 8px;
  background: #fafafa;
  color: var(--text-muted);
  font-size: 11px;
}
 
.img-error-icon {
  font-size: 16px;
}
</style>