perf(image): 图片列表默认加载缩略图

This commit is contained in:
yml
2026-11-24 22:30:37 +08:00
parent 3cc61615f9
commit 43df96a973
22 changed files with 227 additions and 85 deletions
+18 -1
View File
@@ -247,7 +247,14 @@ func (h *Handler) writeObject(c *gin.Context, publicOnly bool) {
}
storageStart := time.Now()
object, err := h.storage.Get(c.Request.Context(), key)
var object *Object
var err error
for _, readKey := range objectReadKeys(key) {
object, err = h.storage.Get(c.Request.Context(), readKey)
if err == nil {
break
}
}
storageMS := float64(time.Since(storageStart).Microseconds()) / 1000
if err != nil {
fields := []zap.Field{
@@ -308,6 +315,16 @@ func (h *Handler) writeObject(c *gin.Context, publicOnly bool) {
}
}
// objectReadKeys 为图片变体提供原图回退,兼容启用缩略图之前上传的历史文件。
func objectReadKeys(key string) []string {
keys := []string{key}
canonical := filekey.Canonical(key)
if canonical != "" && canonical != key {
keys = append(keys, canonical)
}
return keys
}
func isPublicObjectKey(key string) bool {
for _, prefix := range []string{
"home-banner/",
@@ -0,0 +1,37 @@
package file
import (
"reflect"
"testing"
)
func TestObjectReadKeysFallsBackToOriginalImage(t *testing.T) {
tests := []struct {
name string
key string
want []string
}{
{
name: "original key",
key: "listing/account.webp",
want: []string{"listing/account.webp"},
},
{
name: "thumbnail fallback",
key: "listing/account.webp.thumb.jpg",
want: []string{"listing/account.webp.thumb.jpg", "listing/account.webp"},
},
{
name: "medium fallback",
key: "listing/account.webp.medium.jpg",
want: []string{"listing/account.webp.medium.jpg", "listing/account.webp"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := objectReadKeys(tt.key); !reflect.DeepEqual(got, tt.want) {
t.Fatalf("objectReadKeys(%q) = %#v, want %#v", tt.key, got, tt.want)
}
})
}
}
@@ -2,6 +2,7 @@
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { fetchAdminFileBlob, fetchFileBlobByURL } from '@/shared/api/files'
import { isAdminPath } from '@/shared/utils/adminPath'
import { getFileVariantURL } from '@/shared/utils/fileURLs'
const props = defineProps<{
source: string
@@ -11,6 +12,8 @@ const props = defineProps<{
const objectURL = ref('')
const failed = ref(false)
const effectiveAdmin = computed(() => props.admin || isAdminPath(window.location.pathname))
const thumbnailURL = computed(() => getFileVariantURL(props.source, 'thumb'))
const previewURL = computed(() => getFileVariantURL(props.source, 'medium'))
function extractObjectKey(value: string) {
try {
@@ -35,20 +38,32 @@ async function loadImage() {
return
}
try {
const key = extractObjectKey(props.source)
const key = extractObjectKey(thumbnailURL.value)
const blob =
effectiveAdmin.value && key
? await fetchAdminFileBlob(key)
: await fetchFileBlobByURL(props.source)
: await fetchFileBlobByURL(thumbnailURL.value)
objectURL.value = URL.createObjectURL(blob)
} catch {
failed.value = true
}
}
function openImage() {
if (!objectURL.value) return
window.open(objectURL.value, '_blank')
async function openImage() {
try {
const key = extractObjectKey(previewURL.value)
const blob =
effectiveAdmin.value && key
? await fetchAdminFileBlob(key)
: await fetchFileBlobByURL(previewURL.value)
const previewObjectURL = URL.createObjectURL(blob)
window.open(previewObjectURL, '_blank')
window.setTimeout(() => URL.revokeObjectURL(previewObjectURL), 60_000)
} catch {
if (objectURL.value) {
window.open(objectURL.value, '_blank')
}
}
}
watch(() => [props.source, effectiveAdmin.value] as const, loadImage, { immediate: true })
@@ -2,7 +2,7 @@
import { computed, ref, watch } from 'vue'
import { EditPen, FullScreen, Pointer } from '@element-plus/icons-vue'
import type { Listing } from '@/features/listings'
import { formatListingCode } from '@/shared/utils/listingDisplay'
import { formatListingCode, getScreenshotThumbURL } from '@/shared/utils/listingDisplay'
interface ReviewScreenshotItem {
url: string
@@ -13,7 +13,6 @@ interface ReviewScreenshotItem {
const props = defineProps<{
visible: boolean
listing: Listing | null
previewUrls: Record<string, string>
}>()
const emit = defineEmits<{
@@ -140,7 +139,12 @@ function handleEdit(shot: ReviewScreenshotItem) {
@click="handleView(index)"
>
<div class="image-wrapper">
<img :src="previewUrls[shot.url] || shot.url" :alt="shot.label" loading="lazy" />
<img
:src="getScreenshotThumbURL(shot.url)"
:alt="shot.label"
loading="lazy"
decoding="async"
/>
<span v-if="isDefaultScreenshot(shot.url)" class="default-badge">默认占位图</span>
<span class="category-tag">{{ shot.label }}</span>
<div class="image-overlay" @click.stop>
@@ -545,6 +545,7 @@ function hasMore(item: ProcessTimelineEvent) {
preview-teleported
fit="cover"
admin
variant="thumb"
image-class="attachment-img"
fallback-class="attachment-fallback"
/>
@@ -307,6 +307,7 @@ function incomeText(income?: number) {
:key="idx"
:source="url"
:admin="true"
variant="thumb"
:preview-src-list="withdrawal.certificate_urls"
fit="cover"
:image-style="{
@@ -351,6 +352,7 @@ function incomeText(income?: number) {
<AuthImage
:source="withdrawal.payment_proof_url"
admin
variant="thumb"
alt="打款凭证"
class="certificate-image"
:preview-src-list="[withdrawal.payment_proof_url]"
@@ -645,6 +645,7 @@ async function handleArbitrate() {
v-if="evidenceKind(item) === 'image'"
:source="evidenceSource(item)"
admin
variant="thumb"
:alt="evidenceName(item, index)"
image-class="evidence-image"
fallback-class="evidence-image-fallback"
@@ -458,6 +458,7 @@ onBeforeUnmount(() => {
<AuthImage
:source="row.image_url"
fit="contain"
variant="thumb"
:image-style="{ width: '64px', height: '64px', background: '#f7f9fc' }"
:preview-src-list="[row.image_url]"
/>
@@ -883,6 +883,8 @@ function accountTypeLabel(type: string) {
:source="createForm.voucher_url"
alt="凭证预览"
class="voucher-img-preview"
variant="thumb"
:preview-src-list="[createForm.voucher_url]"
/>
</div>
</div>
@@ -948,7 +950,13 @@ function accountTypeLabel(type: string) {
<div v-if="selectedManual.voucher_url" class="detail-row column-row">
<span class="detail-label">打款凭证</span>
<div class="detail-img-container">
<AuthImage :source="selectedManual.voucher_url" alt="凭证" class="detail-voucher-img" />
<AuthImage
:source="selectedManual.voucher_url"
alt="凭证"
class="detail-voucher-img"
variant="thumb"
:preview-src-list="[selectedManual.voucher_url]"
/>
</div>
</div>
<div v-if="selectedManual.status === 'voided'" class="void-info-box">
@@ -1028,6 +1028,7 @@ async function openScreenshot(url: string) {
<AuthImage
:source="url"
admin
variant="thumb"
:alt="`资产截图 ${index + 1}`"
image-class="screenshot-image"
fallback-class="screenshot-image"
@@ -54,6 +54,8 @@ import {
getFaceOwnerText,
getListingConsumablePrice,
getListingResources,
getScreenshotMediumURL,
getScreenshotThumbURL,
getOnlineTimeText,
getResourceQuantity,
getSkinNames,
@@ -144,7 +146,6 @@ const filters = reactive({
sortBy: 'default',
})
const previewURLs = reactive<Record<string, string>>({})
const createdObjectURLs = new Set<string>()
const lastRefreshedAt = ref<string>('')
const shortcutsDialogVisible = ref(false)
@@ -249,7 +250,7 @@ watch(
if (!listing) return
selectedID.value = listing.id
await nextTick()
loadScreenshotPreviews(listing)
prepareScreenshotPreviews(listing)
},
{ immediate: true }
)
@@ -260,7 +261,6 @@ onMounted(() => {
})
onBeforeUnmount(() => {
createdObjectURLs.forEach(url => URL.revokeObjectURL(url))
window.removeEventListener('keydown', handleGlobalKeydown)
})
@@ -455,7 +455,7 @@ async function onPriceAdjustSave(payload: {
function openEvidence(row: Listing) {
evidenceListing.value = row
evidenceDialogVisible.value = true
loadScreenshotPreviews(row)
prepareScreenshotPreviews(row)
}
function money(value: number) {
@@ -780,21 +780,9 @@ function extractObjectKey(url: string) {
}
}
async function loadScreenshotPreviews(row: Listing) {
function prepareScreenshotPreviews(row: Listing) {
for (const url of row.screenshot_urls || []) {
if (previewURLs[url]) continue
if (isDefaultScreenshot(url) || !extractObjectKey(url)) {
previewURLs[url] = url
continue
}
try {
const blob = await fetchAdminFileBlob(extractObjectKey(url))
const objectURL = URL.createObjectURL(blob)
createdObjectURLs.add(objectURL)
previewURLs[url] = objectURL
} catch {
previewURLs[url] = url
}
previewURLs[url] = isDefaultScreenshot(url) ? url : getScreenshotMediumURL(url)
}
}
@@ -890,11 +878,6 @@ function openRawScreenshot(url: string) {
window.open(url, '_blank')
return
}
const preview = previewURLs[url]
if (preview) {
window.open(preview, '_blank')
return
}
try {
const key = extractObjectKey(url)
if (!key) {
@@ -952,7 +935,7 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
evidenceListing.value.screenshot_urls = nextUrls
}
await loadScreenshotPreviews(targetListing)
prepareScreenshotPreviews(targetListing)
editorVisible.value = false
editingScreenshot.value = null
}
@@ -1121,13 +1104,10 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
<div class="queue-main-row">
<div class="queue-thumb">
<img
:src="
previewURLs[item.screenshot_urls?.[0] || ''] ||
item.screenshot_urls?.[0] ||
_defaultScreenshotURL
"
:src="getScreenshotThumbURL(item.screenshot_urls?.[0]) || _defaultScreenshotURL"
alt="缩略图"
loading="lazy"
decoding="async"
@error="onThumbError"
/>
<span v-if="hasDefaultScreenshot(item)" class="thumb-warning-badge">默认图</span>
@@ -1611,7 +1591,12 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
@click="handleCardClick(selectedReviewScreenshots, index)"
>
<div class="image-wrapper">
<img :src="previewURLs[shot.url] || shot.url" :alt="shot.label" loading="lazy" />
<img
:src="getScreenshotThumbURL(shot.url)"
:alt="shot.label"
loading="lazy"
decoding="async"
/>
<span v-if="isDefaultScreenshot(shot.url)" class="default-badge">
<el-icon><Warning /></el-icon> 默认占位图
</span>
@@ -1742,7 +1727,6 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
<AdminListingReviewEvidenceDialog
v-model:visible="evidenceDialogVisible"
:listing="evidenceListing"
:preview-urls="previewURLs"
@view-image="openPreviewDialog($event.images, $event.index)"
@peek-image="startPeekPreview($event.images, $event.index)"
@edit-screenshot="openEditor($event.shot, $event.listing)"
@@ -478,6 +478,8 @@ function statusType(status: string): 'success' | 'danger' {
:source="createForm.voucher_url"
alt="凭证预览"
class="voucher-img-preview"
variant="thumb"
:preview-src-list="[createForm.voucher_url]"
/>
</div>
</div>
@@ -545,6 +547,8 @@ function statusType(status: string): 'success' | 'danger' {
:source="selectedExpense.voucher_url"
alt="凭证"
class="detail-voucher-img"
variant="thumb"
:preview-src-list="[selectedExpense.voucher_url]"
/>
</div>
</div>
@@ -696,6 +696,7 @@ onMounted(reloadAll)
<AuthImage
:source="row.image_url"
fit="cover"
variant="thumb"
:image-style="{ width: '56px', height: '56px', borderRadius: '6px' }"
:preview-src-list="[row.image_url]"
/>
@@ -837,6 +838,7 @@ onMounted(reloadAll)
v-if="img.url"
:source="img.url"
fit="cover"
variant="thumb"
:image-style="{ width: '52px', height: '52px', borderRadius: '6px' }"
:preview-src-list="[img.url]"
/>
@@ -910,6 +912,7 @@ onMounted(reloadAll)
v-if="editForm.image_url"
:source="editForm.image_url"
fit="cover"
variant="thumb"
:preview-src-list="[editForm.image_url]"
:image-style="{ width: '100%', height: '100%', borderRadius: '6px' }"
/>
@@ -255,6 +255,7 @@ const hasContent = computed(() => Boolean(snapshot.value))
<AuthImage
:source="shot.url"
:alt="shot.label"
variant="thumb"
image-class="shot-img"
fit="cover"
:preview-src-list="screenshotUrls"
@@ -314,6 +315,7 @@ const hasContent = computed(() => Boolean(snapshot.value))
<AuthImage
:source="shot.url"
:alt="shot.label"
variant="thumb"
image-class="shot-img"
fit="cover"
:preview-src-list="screenshotUrls"
@@ -253,6 +253,7 @@ async function handleOffline() {
<AuthImage
:source="detailScreenshots[0].url"
:alt="getListingTitle(listing)"
variant="thumb"
image-class="cover-img"
fit="cover"
:preview-src-list="detailScreenshotUrls"
@@ -333,6 +334,7 @@ async function handleOffline() {
<AuthImage
:source="shot.url"
:alt="shot.label"
variant="thumb"
image-class="shot-img"
fit="cover"
:preview-src-list="detailScreenshotUrls"
@@ -335,6 +335,7 @@ async function handleOffline() {
<AuthImage
:source="shot.url"
:alt="shot.label"
variant="thumb"
image-class="shot-img"
fit="cover"
:preview-src-list="detailScreenshotUrls"
@@ -260,6 +260,7 @@ function removeImage(index: number) {
:source="url"
alt="凭证"
fit="cover"
variant="thumb"
:preview-src-list="form.certificate_urls"
:preview-initial-index="index"
/>
@@ -633,6 +633,7 @@ function statusType(status: string): 'primary' | 'success' | 'danger' | 'warning
:source="url"
alt="收款凭证"
fit="cover"
variant="thumb"
:preview-src-list="accountForm.certificate_urls"
:preview-initial-index="index"
/>
@@ -2,6 +2,7 @@
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { fetchAdminFileBlob, fetchFileAccessTicket, fetchFileBlobByURL } from '@/shared/api/files'
import { isAdminPath } from '@/shared/utils/adminPath'
import { getFileVariantURL, type FileImageVariant } from '@/shared/utils/fileURLs'
const props = withDefaults(
defineProps<{
@@ -15,6 +16,8 @@ const props = withDefaults(
previewSrcList?: string[]
previewTeleported?: boolean
previewInitialIndex?: number
variant?: FileImageVariant
previewVariant?: FileImageVariant
fit?: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down'
imageStyle?: any
}>(),
@@ -25,6 +28,8 @@ const props = withDefaults(
fallbackClass: '',
loading: 'lazy',
decoding: 'async',
variant: 'raw',
previewVariant: 'medium',
previewTeleported: true,
previewInitialIndex: 0,
}
@@ -46,6 +51,7 @@ const imageStyleValue = computed(() => {
if (!props.fit) return props.imageStyle
return [props.imageStyle, { objectFit: props.fit }]
})
const sourceVariantURL = computed(() => getFileVariantURL(props.source, props.variant))
const previewSignature = computed(() => props.previewSrcList?.join('\u0000') || '')
function withAuthImageLoadSlot<T>(task: () => Promise<T>): Promise<T> {
@@ -130,39 +136,30 @@ async function loadImage() {
}
try {
const sourceURL = await resolveURL(props.source)
const sourceURL = await resolveURL(sourceVariantURL.value)
imageURL.value = sourceURL
if (props.previewSrcList?.length) {
// 先填充公开或当前已解析的主图 URL,让预览组件立即可用
const initialPreviews = props.previewSrcList.map(url =>
url === props.source ? sourceURL : url
previewURLs.value = props.previewSrcList.map(url =>
url === props.source ? sourceURL : getFileVariantURL(url, props.previewVariant)
)
previewURLs.value = initialPreviews
// 若包含需要鉴权转 Blob 的私有 URL,在后台异步静默解析,不阻塞主图呈现
const hasAuthPreviews = props.previewSrcList.some(
url => url !== props.source && shouldFetchWithAuth(url)
)
if (hasAuthPreviews) {
Promise.all(
props.previewSrcList.map(url => (url === props.source ? sourceURL : resolveURL(url)))
)
.then(urls => {
previewURLs.value = urls
})
.catch(() => {
// 预览图静默降级,不破坏主图正常显示
})
}
}
} catch {
failed.value = true
}
}
watch(() => [props.source, effectiveAdmin.value, previewSignature.value] as const, loadImage, {
immediate: true,
})
watch(
() =>
[
props.source,
props.variant,
props.previewVariant,
effectiveAdmin.value,
previewSignature.value,
] as const,
loadImage,
{ immediate: true }
)
onBeforeUnmount(cleanup)
</script>
@@ -6,6 +6,9 @@ import {
getListingResources,
getListingSellerCoinPrice,
getListingSellerPrice,
getScreenshotMediumURL,
getScreenshotRawURL,
getScreenshotThumbURL,
isNonOwnFace,
} from '../listingDisplay'
import type { PublicListingItem } from '@/features/listings/api/listings'
@@ -99,6 +102,39 @@ describe('本人人脸展示', () => {
})
})
describe('截图变体 URL', () => {
const objectURL = '/api/files/object?key=listing%2F2026%2F11%2Faccount.webp'
it('私有对象 URL 使用已生成的缩略图和中等图', () => {
expect(getScreenshotThumbURL(objectURL)).toBe(
'/api/files/object?key=listing%2F2026%2F11%2Faccount.thumb.jpg'
)
expect(getScreenshotMediumURL(objectURL)).toBe(
'/api/files/object?key=listing%2F2026%2F11%2Faccount.medium.jpg'
)
})
it('原图 URL 不做变体转换', () => {
expect(getScreenshotRawURL(objectURL)).toBe(objectURL)
})
it('已带图片变体的 URL 不会重复叠加后缀', () => {
const mediumURL = '/api/files/object?key=listing%2Faccount.webp.medium.jpg'
expect(getScreenshotMediumURL(mediumURL)).toBe(
'/api/files/object?key=listing%2Faccount.medium.jpg'
)
expect(getScreenshotThumbURL(mediumURL)).toBe(
'/api/files/object?key=listing%2Faccount.thumb.jpg'
)
})
it('兼容公开截图站点的 variant 参数', () => {
expect(getScreenshotThumbURL('/api/listings/1/screenshots/0')).toBe(
'/api/listings/1/screenshots/0?variant=thumb'
)
})
})
describe('首页规格芯片 · 德穆兰优先级高于全英雄', () => {
it('解锁德穆兰时用「解锁德穆兰」替换「全英雄」', () => {
const chips = getListingChips(buildListing({ all_hero: '是', unlock_demulan: '是' }))
+38
View File
@@ -0,0 +1,38 @@
export type FileImageVariant = 'thumb' | 'medium' | 'raw'
function withObjectVariant(url: string, variant: Exclude<FileImageVariant, 'raw'>): string {
const separatorIndex = url.indexOf('?')
const pathname = separatorIndex >= 0 ? url.slice(0, separatorIndex) : url
if (!pathname.endsWith('/files/object')) return ''
const params = new URLSearchParams(separatorIndex >= 0 ? url.slice(separatorIndex + 1) : '')
const key = params.get('key') || ''
if (!key) return ''
const withoutVariant = key.replace(/\.(?:thumb|medium)\.jpg$/i, '')
const slashIndex = withoutVariant.lastIndexOf('/')
const dotIndex = withoutVariant.lastIndexOf('.')
const base = dotIndex > slashIndex ? withoutVariant.slice(0, dotIndex) : withoutVariant
params.set('key', `${base}.${variant}.jpg`)
return `${pathname}?${params.toString()}`
}
/**
* 将私有对象或公开截图地址转换为上传时生成的图片变体。
* 非图片对象、外链和无法识别的地址保持原样。
*/
export function getFileVariantURL(
url: string | undefined | null,
variant: FileImageVariant
): string {
if (!url) return ''
if (variant === 'raw') return url
const objectVariantURL = withObjectVariant(url, variant)
if (objectVariantURL) return objectVariantURL
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=${variant}`
}
return url
}
+6 -20
View File
@@ -1,4 +1,5 @@
import type { Listing, PublicListingItem } from '@/features/listings/api/listings'
import { getFileVariantURL } from '@/shared/utils/fileURLs'
import { centToYuan } from '@/shared/utils/money'
export interface ListingDisplayChip {
@@ -436,37 +437,22 @@ export function getCoinScreenshotURL(item: Listing): string {
}
/**
* 转换截图为缩略图 URL(优先使用 16KB 极速缩略图,秒级加载)
* 转换截图为缩略图 URL(优先使用上传时生成的缩略图,秒级加载)
*/
export function getScreenshotThumbURL(url: string | undefined | null): string {
if (!url) return ''
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=thumb`
}
return url
return getFileVariantURL(url, 'thumb')
}
/**
* 转换截图为中等图 URL(1280px,100KB左右,清晰秒开)
* 转换截图为中等图 URL(1280px,100KB左右,适合弹窗预览)
*/
export function getScreenshotMediumURL(url: string | undefined | null): string {
if (!url) return ''
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=medium`
}
return url
return getFileVariantURL(url, 'medium')
}
/**
* 转换截图为原始高清原图 URL(用于全屏放大查看细节)
*/
export function getScreenshotRawURL(url: string | undefined | null): string {
if (!url) return ''
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=raw`
}
return url
return getFileVariantURL(url, 'raw')
}