From 43df96a973c40c9c07550d5a9a922aaba2398633 Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 24 Nov 2026 22:30:37 +0800 Subject: [PATCH] =?UTF-8?q?perf(image):=20=E5=9B=BE=E7=89=87=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E9=BB=98=E8=AE=A4=E5=8A=A0=E8=BD=BD=E7=BC=A9=E7=95=A5?= =?UTF-8?q?=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/modules/file/handler.go | 19 +++++++- backend/internal/modules/file/handler_test.go | 37 +++++++++++++++ .../src/components/ChatAttachmentImage.vue | 25 ++++++++-- .../AdminListingReviewEvidenceDialog.vue | 10 ++-- .../admin/components/ProcessTimeline.vue | 1 + .../components/WithdrawalDetailDialog.vue | 2 + .../admin/views/AdminDisputesView.vue | 1 + .../views/AdminDistributionQrCodePoolView.vue | 1 + .../views/AdminFinanceDisbursementsView.vue | 10 +++- .../admin/views/AdminListingDetailView.vue | 1 + .../admin/views/AdminListingReviewView.vue | 46 ++++++------------- .../views/AdminOperatingExpensesView.vue | 4 ++ .../admin/views/AdminQrCodePoolView.vue | 3 ++ .../components/OrderAccountSnapshot.vue | 2 + .../views/MobileSellerListingDetailView.vue | 2 + .../seller/views/SellerListingDetailView.vue | 1 + .../components/PaymentAccountDialog.vue | 1 + .../wallet/views/MobileWithdrawalView.vue | 1 + .../shared/components/business/AuthImage.vue | 45 +++++++++--------- .../utils/__tests__/listingDisplay.spec.ts | 36 +++++++++++++++ frontend/src/shared/utils/fileURLs.ts | 38 +++++++++++++++ frontend/src/shared/utils/listingDisplay.ts | 26 +++-------- 22 files changed, 227 insertions(+), 85 deletions(-) create mode 100644 backend/internal/modules/file/handler_test.go create mode 100644 frontend/src/shared/utils/fileURLs.ts diff --git a/backend/internal/modules/file/handler.go b/backend/internal/modules/file/handler.go index a0cfa4d5..ed03df1f 100644 --- a/backend/internal/modules/file/handler.go +++ b/backend/internal/modules/file/handler.go @@ -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/", diff --git a/backend/internal/modules/file/handler_test.go b/backend/internal/modules/file/handler_test.go new file mode 100644 index 00000000..7944e600 --- /dev/null +++ b/backend/internal/modules/file/handler_test.go @@ -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) + } + }) + } +} diff --git a/frontend/src/components/ChatAttachmentImage.vue b/frontend/src/components/ChatAttachmentImage.vue index 126f5314..cfa9e9ec 100644 --- a/frontend/src/components/ChatAttachmentImage.vue +++ b/frontend/src/components/ChatAttachmentImage.vue @@ -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 }) diff --git a/frontend/src/features/admin/components/AdminListingReviewEvidenceDialog.vue b/frontend/src/features/admin/components/AdminListingReviewEvidenceDialog.vue index ca5f9eda..49fa3bd9 100644 --- a/frontend/src/features/admin/components/AdminListingReviewEvidenceDialog.vue +++ b/frontend/src/features/admin/components/AdminListingReviewEvidenceDialog.vue @@ -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 }>() const emit = defineEmits<{ @@ -140,7 +139,12 @@ function handleEdit(shot: ReviewScreenshotItem) { @click="handleView(index)" >
- + 默认占位图 {{ shot.label }}
diff --git a/frontend/src/features/admin/components/ProcessTimeline.vue b/frontend/src/features/admin/components/ProcessTimeline.vue index f06222d7..a6dde9d6 100644 --- a/frontend/src/features/admin/components/ProcessTimeline.vue +++ b/frontend/src/features/admin/components/ProcessTimeline.vue @@ -545,6 +545,7 @@ function hasMore(item: ProcessTimelineEvent) { preview-teleported fit="cover" admin + variant="thumb" image-class="attachment-img" fallback-class="attachment-fallback" /> diff --git a/frontend/src/features/admin/components/WithdrawalDetailDialog.vue b/frontend/src/features/admin/components/WithdrawalDetailDialog.vue index eabf1407..6eb4089b 100644 --- a/frontend/src/features/admin/components/WithdrawalDetailDialog.vue +++ b/frontend/src/features/admin/components/WithdrawalDetailDialog.vue @@ -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) { { diff --git a/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue b/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue index 5b290476..17dbcaed 100644 --- a/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue +++ b/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue @@ -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]" />
@@ -948,7 +950,13 @@ function accountTypeLabel(type: string) {
打款凭证
- +
diff --git a/frontend/src/features/admin/views/AdminListingDetailView.vue b/frontend/src/features/admin/views/AdminListingDetailView.vue index 108f893a..ab169f49 100644 --- a/frontend/src/features/admin/views/AdminListingDetailView.vue +++ b/frontend/src/features/admin/views/AdminListingDetailView.vue @@ -1028,6 +1028,7 @@ async function openScreenshot(url: string) { >({}) -const createdObjectURLs = new Set() const lastRefreshedAt = ref('') 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 }
缩略图 默认图 @@ -1611,7 +1591,12 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string } @click="handleCardClick(selectedReviewScreenshots, index)" >
- + 默认占位图 @@ -1742,7 +1727,6 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
@@ -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]" />
diff --git a/frontend/src/features/admin/views/AdminQrCodePoolView.vue b/frontend/src/features/admin/views/AdminQrCodePoolView.vue index ef78aac3..41311573 100644 --- a/frontend/src/features/admin/views/AdminQrCodePoolView.vue +++ b/frontend/src/features/admin/views/AdminQrCodePoolView.vue @@ -696,6 +696,7 @@ onMounted(reloadAll) @@ -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' }" /> diff --git a/frontend/src/features/orders/components/OrderAccountSnapshot.vue b/frontend/src/features/orders/components/OrderAccountSnapshot.vue index 25760730..8884bdd6 100644 --- a/frontend/src/features/orders/components/OrderAccountSnapshot.vue +++ b/frontend/src/features/orders/components/OrderAccountSnapshot.vue @@ -255,6 +255,7 @@ const hasContent = computed(() => Boolean(snapshot.value)) Boolean(snapshot.value)) diff --git a/frontend/src/features/wallet/views/MobileWithdrawalView.vue b/frontend/src/features/wallet/views/MobileWithdrawalView.vue index 89520664..2325f2ef 100644 --- a/frontend/src/features/wallet/views/MobileWithdrawalView.vue +++ b/frontend/src/features/wallet/views/MobileWithdrawalView.vue @@ -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" /> diff --git a/frontend/src/shared/components/business/AuthImage.vue b/frontend/src/shared/components/business/AuthImage.vue index 415d9d07..4303f15c 100644 --- a/frontend/src/shared/components/business/AuthImage.vue +++ b/frontend/src/shared/components/business/AuthImage.vue @@ -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(task: () => Promise): Promise { @@ -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) diff --git a/frontend/src/shared/utils/__tests__/listingDisplay.spec.ts b/frontend/src/shared/utils/__tests__/listingDisplay.spec.ts index 9b69431f..a9fc7548 100644 --- a/frontend/src/shared/utils/__tests__/listingDisplay.spec.ts +++ b/frontend/src/shared/utils/__tests__/listingDisplay.spec.ts @@ -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: '是' })) diff --git a/frontend/src/shared/utils/fileURLs.ts b/frontend/src/shared/utils/fileURLs.ts new file mode 100644 index 00000000..5ebc7ec6 --- /dev/null +++ b/frontend/src/shared/utils/fileURLs.ts @@ -0,0 +1,38 @@ +export type FileImageVariant = 'thumb' | 'medium' | 'raw' + +function withObjectVariant(url: string, variant: Exclude): 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 +} diff --git a/frontend/src/shared/utils/listingDisplay.ts b/frontend/src/shared/utils/listingDisplay.ts index 181e841b..f5c10d02 100644 --- a/frontend/src/shared/utils/listingDisplay.ts +++ b/frontend/src/shared/utils/listingDisplay.ts @@ -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') }