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