fix(uploads): downscale huge-dimension files and give thumbnails a fallback
A flat 8000x8000 PNG can weigh 13 KB, so the byte-size shortcut skipped compression and every thumbnail render had to decode 64 MP first — on a small server that outlived nginx's timeout, leaving the card broken until the variant finished while the original (/uploads) opened fine. Files over 2000 px on their long side are now converted even when they are small on disk. ant-design-vue paints the upload tile as <img src=thumbUrl alt=name> with no error handling, so any failed resize showed the grey box with just the file name. The tile now falls back to the stored original. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Haiku 5.5
parent
41399a33bb
commit
0b54752b6f
@@ -10,7 +10,7 @@
|
||||
|
||||
The bound value is the stored file's URL, which is what the schema keeps.
|
||||
-->
|
||||
<div class="image-upload">
|
||||
<div class="image-upload" @error.capture="onThumbError">
|
||||
<a-upload
|
||||
:file-list="fileList"
|
||||
list-type="picture-card"
|
||||
@@ -91,6 +91,24 @@ watch(
|
||||
|
||||
const placeholder = computed(() => props.placeholder);
|
||||
|
||||
/**
|
||||
* ant-design-vue paints the tile as `<img :src="thumbUrl || url" alt=name>`
|
||||
* with no error handling of its own, so a failed resize (a 404/504 from
|
||||
* /api/img, or a variant still rendering) left the card grey with only the
|
||||
* file name — which is what an admin saw right after uploading. Swap the
|
||||
* thumbnail for the stored original, which the eye preview already loads.
|
||||
* Capture phase: `error` on an <img> does not bubble.
|
||||
*/
|
||||
function onThumbError(e: Event) {
|
||||
const img = e.target as HTMLImageElement | null;
|
||||
const original = fileList.value[0]?.url;
|
||||
if (!img || img.tagName !== 'IMG' || !original) return;
|
||||
// Compare paths, not the whole URL: the browser resolves src absolutely.
|
||||
if (new URL(img.src, window.location.origin).pathname !== original) {
|
||||
img.src = original;
|
||||
}
|
||||
}
|
||||
|
||||
function beforeUpload(file: File) {
|
||||
const problem = checkImageFile(file);
|
||||
if (problem) {
|
||||
|
||||
@@ -63,7 +63,11 @@ describe('ImageVariantService', () => {
|
||||
const big = Buffer.alloc(3000 * KB);
|
||||
|
||||
/** A sharp stand-in whose output size depends on the requested quality and side. */
|
||||
function fakeSharp(svc: ImageVariantService, sizeFor: (side: number, quality: number) => number) {
|
||||
function fakeSharp(
|
||||
svc: ImageVariantService,
|
||||
sizeFor: (side: number, quality: number) => number,
|
||||
dims: { width: number; height: number } = { width: 1600, height: 1200 },
|
||||
) {
|
||||
const calls: Array<{ side: number; quality: number }> = [];
|
||||
(svc as unknown as { sharp: unknown }).sharp = () => {
|
||||
let side = 0;
|
||||
@@ -72,6 +76,7 @@ describe('ImageVariantService', () => {
|
||||
rotate: () => p,
|
||||
resize: (o: { width: number }) => ((side = o.width), p),
|
||||
webp: (o: { quality: number }) => ((quality = o.quality), p),
|
||||
metadata: async () => dims,
|
||||
toFile: jest.fn(),
|
||||
toBuffer: async () => {
|
||||
calls.push({ side, quality });
|
||||
@@ -135,6 +140,17 @@ describe('ImageVariantService', () => {
|
||||
const heic = await svc.compressUpload(Buffer.alloc(20 * KB), 'image/heic', 'photo.heic');
|
||||
expect(heic).toMatchObject({ ext: '.webp' });
|
||||
});
|
||||
|
||||
it('downscales a small file with huge dimensions', async () => {
|
||||
const svc = new ImageVariantService();
|
||||
// 13 KB on disk, 6400×6400 when decoded: every thumbnail render would
|
||||
// have to decode 41 MP first.
|
||||
const calls = fakeSharp(svc, () => 40 * KB, { width: 6400, height: 6400 });
|
||||
|
||||
const out = await svc.compressUpload(Buffer.alloc(13 * KB), 'image/png', 'flat.png');
|
||||
expect(calls.length).toBeGreaterThan(0);
|
||||
expect(out).toMatchObject({ ext: '.webp' });
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to the original when a render fails', async () => {
|
||||
|
||||
@@ -63,6 +63,7 @@ interface SharpPipeline {
|
||||
withoutEnlargement: boolean;
|
||||
}): SharpPipeline;
|
||||
webp(opts: { quality: number }): SharpPipeline;
|
||||
metadata(): Promise<{ width?: number; height?: number }>;
|
||||
toFile(path: string): Promise<unknown>;
|
||||
toBuffer(): Promise<Buffer>;
|
||||
}
|
||||
@@ -146,10 +147,26 @@ export class ImageVariantService {
|
||||
// Small uploads are kept as sent — except formats browsers cannot paint,
|
||||
// which are always converted so the card thumbnail is never broken.
|
||||
const mustConvert = BROWSER_UNSAFE_MIME.has(mimeType);
|
||||
if (buffer.length <= ORIGINAL_TARGET_BYTES && !mustConvert) return null;
|
||||
const sharp = this.loadSharp();
|
||||
if (!sharp) return null;
|
||||
|
||||
let oversized = false;
|
||||
if (!mustConvert && buffer.length <= ORIGINAL_TARGET_BYTES) {
|
||||
// Bytes are not size: a flat 8000×8000 PNG can be 13 KB. Keeping one
|
||||
// means every thumbnail render has to decode 64 MP first, which on a
|
||||
// small server outlives nginx's timeout — the card showed a broken
|
||||
// image until the variant finally finished. Downscale those too.
|
||||
try {
|
||||
const meta = await sharp(buffer, { failOn: 'none', limitInputPixels: MAX_INPUT_PIXELS }).metadata();
|
||||
const side = Math.max(meta.width ?? 0, meta.height ?? 0);
|
||||
if (side <= ORIGINAL_ATTEMPTS[0].side) return null;
|
||||
oversized = true;
|
||||
} catch (err) {
|
||||
this.logger.warn(`metadata failed for ${filename}: ${(err as Error).message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let smallest: Buffer | null = null;
|
||||
try {
|
||||
for (const { side, quality } of ORIGINAL_ATTEMPTS) {
|
||||
@@ -167,8 +184,10 @@ export class ImageVariantService {
|
||||
}
|
||||
|
||||
if (!smallest) return null;
|
||||
// A conversion is mandatory for browser-unsafe formats even if larger.
|
||||
if (!mustConvert && smallest.length >= buffer.length) return null;
|
||||
// A conversion is mandatory for browser-unsafe formats even if larger, and
|
||||
// a huge-dimension source is worth a few extra KB: every later resize of
|
||||
// it stays cheap.
|
||||
if (!mustConvert && !oversized && smallest.length >= buffer.length) return null;
|
||||
if (smallest.length > ORIGINAL_CEILING_BYTES) {
|
||||
this.logger.warn(`${filename} is still ${smallest.length} bytes after compression`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user