feat(uploads): accept 15 MB / 8000px and every standard image format
- API ceiling 8 MB -> 15 MB, sharp limitInputPixels 64 MP (8000x8000) - accept AVIF, BMP, TIFF, HEIC/HEIF, JXL alongside JPEG/PNG/WebP/GIF/SVG/PDF; fall back to the file extension when the browser sends an empty or octet-stream type - convert formats browsers cannot paint (TIFF, HEIC, JXL) to WebP on upload - pre-warm 200/400/600/1600 variants so card thumbnails never wait on a render - nginx: client_max_body_size 20m, proxy_read_timeout 180s (the 1m default rejected every real photo with a bare 413, and a slow 8000px render became a 504 that left the card thumbnail broken while /uploads worked) - gallery tile falls back to the original file if a variant fails Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
072344f85e
commit
387222851c
@@ -18,6 +18,12 @@ import { masterOtpCode, masterOtpEnabled } from './modules/customer-auth/custome
|
||||
// content), but a strict client or an <img> under some CSPs would not.
|
||||
const EXTRA_MIME_TYPES: Record<string, string> = {
|
||||
'.avif': 'image/avif',
|
||||
'.bmp': 'image/bmp',
|
||||
'.tif': 'image/tiff',
|
||||
'.tiff': 'image/tiff',
|
||||
'.heic': 'image/heic',
|
||||
'.heif': 'image/heif',
|
||||
'.jxl': 'image/jxl',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -68,10 +68,24 @@ describe('AdminUploadsService.store', () => {
|
||||
|
||||
await expect(svc.store(undefined, undefined, null)).rejects.toThrow('فایلی انتخاب نشده است');
|
||||
await expect(
|
||||
svc.store(file({ buffer: Buffer.alloc(8 * 1024 * 1024 + 1) }), undefined, null),
|
||||
).rejects.toThrow('بیشتر از ۸ مگابایت');
|
||||
svc.store(file({ buffer: Buffer.alloc(15 * 1024 * 1024 + 1) }), undefined, null),
|
||||
).rejects.toThrow('بیشتر از ۱۵ مگابایت');
|
||||
await expect(
|
||||
svc.store(file({ originalname: 'a.heic', mimetype: 'image/heic' }), undefined, null),
|
||||
svc.store(file({ originalname: 'setup.exe', mimetype: 'application/x-msdownload' }), undefined, null),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('accepts every standard image format, including HEIC and TIFF', async () => {
|
||||
const { svc } = build(async () => null);
|
||||
for (const [name, mime] of [
|
||||
['photo.heic', 'image/heic'],
|
||||
['scan.tiff', 'image/tiff'],
|
||||
['art.bmp', 'image/bmp'],
|
||||
['pic.avif', 'image/avif'],
|
||||
['logo.svg', 'image/svg+xml'],
|
||||
]) {
|
||||
await expect(svc.store(file({ originalname: name, mimetype: mime }), undefined, null)).resolves
|
||||
.toMatchObject({ originalName: name });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { extname, join } from 'node:path';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { ImageVariantService } from './image-variants.service';
|
||||
import { getUploadDir } from './upload-path';
|
||||
import { getUploadDir, mimeForUpload } from './upload-path';
|
||||
|
||||
/**
|
||||
* File uploads — ports legacy `POST file/create`
|
||||
@@ -30,11 +30,17 @@ export class AdminUploadsService {
|
||||
private readonly dir = getUploadDir();
|
||||
|
||||
/** Mirrors legacy's `type` field: 1 = image, 2 = any other document. */
|
||||
private static readonly IMAGE_MIME = /^image\/(jpeg|png|gif|webp|svg\+xml)$/;
|
||||
private static readonly ALLOWED = /^(image\/(jpeg|png|gif|webp|svg\+xml)|application\/pdf)$/;
|
||||
private static readonly IMAGE_MIME =
|
||||
/^image\/(jpeg|jpg|pjpeg|png|apng|gif|webp|svg\+xml|avif|bmp|x-ms-bmp|tiff|heic|heif|jxl)$/;
|
||||
private static readonly ALLOWED =
|
||||
/^(image\/(jpeg|jpg|pjpeg|png|apng|gif|webp|svg\+xml|avif|bmp|x-ms-bmp|tiff|heic|heif|jxl)|application\/pdf)$/;
|
||||
|
||||
/** 8 MB. Legacy relied on PHP's upload_max_filesize; this makes it explicit. */
|
||||
private static readonly MAX_BYTES = 8 * 1024 * 1024;
|
||||
/**
|
||||
* 15 MB. Legacy relied on PHP's upload_max_filesize; this makes it explicit.
|
||||
* The ceiling is paired with ImageVariantService's `limitInputPixels`, which
|
||||
* accepts up to 8000×8000 (64 MP) rasters.
|
||||
*/
|
||||
private static readonly MAX_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
@@ -47,14 +53,20 @@ export class AdminUploadsService {
|
||||
actorAdminUserId: string | null,
|
||||
) {
|
||||
if (!file) throw new BadRequestException('فایلی انتخاب نشده است');
|
||||
// Some browsers and OSes send an empty type or application/octet-stream
|
||||
// for formats they do not have registered (HEIC, TIFF, JXL...). Fall back
|
||||
// to the extension so those uploads are not rejected for a missing label.
|
||||
const mime = mimeForUpload(file.originalname) ?? file.mimetype;
|
||||
if (file.size > AdminUploadsService.MAX_BYTES) {
|
||||
throw new BadRequestException('حجم فایل بیشتر از ۸ مگابایت است؛ فایل کوچکتری انتخاب کنید');
|
||||
throw new BadRequestException('حجم فایل بیشتر از ۱۵ مگابایت است؛ فایل کوچکتری انتخاب کنید');
|
||||
}
|
||||
if (!AdminUploadsService.ALLOWED.test(file.mimetype)) {
|
||||
throw new BadRequestException('این نوع فایل پشتیبانی نمیشود؛ فقط JPG، PNG، WebP، GIF، SVG یا PDF');
|
||||
if (!AdminUploadsService.ALLOWED.test(mime)) {
|
||||
throw new BadRequestException(
|
||||
'این نوع فایل پشتیبانی نمیشود؛ تصویر JPG، PNG، WebP، GIF، SVG، AVIF، BMP، TIFF، HEIC یا سند PDF انتخاب کنید',
|
||||
);
|
||||
}
|
||||
|
||||
const compressed = await this.variants.compressUpload(file.buffer, file.mimetype, file.originalname);
|
||||
const compressed = await this.variants.compressUpload(file.buffer, mime, file.originalname);
|
||||
const buffer = compressed?.buffer ?? file.buffer;
|
||||
|
||||
// legacy: md5(time() . original_name) . '.' . ext
|
||||
@@ -71,7 +83,7 @@ export class AdminUploadsService {
|
||||
data: {
|
||||
url: `/uploads/${stored}`,
|
||||
originalName: file.originalname,
|
||||
mimeType: compressed?.mimeType ?? file.mimetype,
|
||||
mimeType: compressed?.mimeType ?? mime,
|
||||
sizeBytes: buffer.length,
|
||||
purpose: purpose ?? null,
|
||||
uploadedByAdminId: actorAdminUserId,
|
||||
|
||||
@@ -123,6 +123,18 @@ describe('ImageVariantService', () => {
|
||||
fakeSharp(svc, () => 4000 * KB);
|
||||
await expect(svc.compressUpload(big, 'image/webp', 'a.webp')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('always converts formats browsers cannot display, even when small', async () => {
|
||||
const svc = new ImageVariantService();
|
||||
const calls = fakeSharp(svc, () => 10 * KB);
|
||||
|
||||
const out = await svc.compressUpload(Buffer.alloc(20 * KB), 'image/tiff', 'scan.tiff');
|
||||
expect(calls).toHaveLength(5);
|
||||
expect(out).toMatchObject({ ext: '.webp', mimeType: 'image/webp' });
|
||||
|
||||
const heic = await svc.compressUpload(Buffer.alloc(20 * KB), 'image/heic', 'photo.heic');
|
||||
expect(heic).toMatchObject({ ext: '.webp' });
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to the original when a render fails', async () => {
|
||||
|
||||
@@ -8,11 +8,35 @@ export const IMAGE_WIDTHS = [200, 400, 600, 800, 1200, 1600] as const;
|
||||
export type ImageWidth = (typeof IMAGE_WIDTHS)[number];
|
||||
|
||||
/** Rendered right after an upload so the first shopper never waits on a resize. */
|
||||
const WARM_WIDTHS: ImageWidth[] = [600, 1600];
|
||||
const WARM_WIDTHS: ImageWidth[] = [200, 400, 600, 1600];
|
||||
|
||||
/** GIF is skipped so animations survive; SVG and PDF are not raster. */
|
||||
const RESIZABLE = new Set(['.jpg', '.jpeg', '.png', '.webp', '.avif']);
|
||||
const RESIZABLE_MIME = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/avif']);
|
||||
const RESIZABLE = new Set(['.jpg', '.jpeg', '.png', '.webp', '.avif', '.bmp', '.tif', '.tiff', '.heic', '.heif']);
|
||||
const RESIZABLE_MIME = new Set([
|
||||
'image/jpeg',
|
||||
'image/jpg',
|
||||
'image/pjpeg',
|
||||
'image/png',
|
||||
'image/apng',
|
||||
'image/webp',
|
||||
'image/avif',
|
||||
'image/bmp',
|
||||
'image/x-ms-bmp',
|
||||
'image/tiff',
|
||||
'image/heic',
|
||||
'image/heif',
|
||||
'image/jxl',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Formats a browser may fail to display at all (TIFF, HEIC/HEIF, JXL, some
|
||||
* BMPs). Those are always re-encoded to WebP — even when the file is small —
|
||||
* so a stored upload is never a card thumbnail the browser cannot paint.
|
||||
*/
|
||||
const BROWSER_UNSAFE_MIME = new Set(['image/tiff', 'image/heic', 'image/heif', 'image/jxl']);
|
||||
|
||||
/** 8000×8000, the largest upload the panel accepts. */
|
||||
const MAX_INPUT_PIXELS = 8000 * 8000;
|
||||
|
||||
const WEBP_QUALITY = 78;
|
||||
|
||||
@@ -42,7 +66,10 @@ interface SharpPipeline {
|
||||
toFile(path: string): Promise<unknown>;
|
||||
toBuffer(): Promise<Buffer>;
|
||||
}
|
||||
type SharpFactory = (input: string | Buffer, opts?: { failOn?: 'none' }) => SharpPipeline;
|
||||
type SharpFactory = (
|
||||
input: string | Buffer,
|
||||
opts?: { failOn?: 'none'; limitInputPixels?: number },
|
||||
) => SharpPipeline;
|
||||
|
||||
export interface CompressedUpload {
|
||||
buffer: Buffer;
|
||||
@@ -115,28 +142,33 @@ export class ImageVariantService {
|
||||
mimeType: string,
|
||||
filename: string,
|
||||
): Promise<CompressedUpload | null> {
|
||||
if (buffer.length <= ORIGINAL_TARGET_BYTES) return null;
|
||||
if (!RESIZABLE_MIME.has(mimeType)) return null;
|
||||
// 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 smallest: Buffer | null = null;
|
||||
try {
|
||||
for (const { side, quality } of ORIGINAL_ATTEMPTS) {
|
||||
const out = await sharp(buffer, { failOn: 'none' })
|
||||
const out = await sharp(buffer, { failOn: 'none', limitInputPixels: MAX_INPUT_PIXELS })
|
||||
.rotate()
|
||||
.resize({ width: side, height: side, fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality })
|
||||
.toBuffer();
|
||||
if (!smallest || out.length < smallest.length) smallest = out;
|
||||
if (out.length <= ORIGINAL_TARGET_BYTES) break;
|
||||
if (out.length <= ORIGINAL_TARGET_BYTES && !mustConvert) break;
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(`compress failed for ${filename}: ${(err as Error).message}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!smallest || smallest.length >= buffer.length) return null;
|
||||
if (!smallest) return null;
|
||||
// A conversion is mandatory for browser-unsafe formats even if larger.
|
||||
if (!mustConvert && smallest.length >= buffer.length) return null;
|
||||
if (smallest.length > ORIGINAL_CEILING_BYTES) {
|
||||
this.logger.warn(`${filename} is still ${smallest.length} bytes after compression`);
|
||||
}
|
||||
@@ -168,7 +200,7 @@ export class ImageVariantService {
|
||||
const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await sharp(original, { failOn: 'none' })
|
||||
await sharp(original, { failOn: 'none', limitInputPixels: MAX_INPUT_PIXELS })
|
||||
.rotate()
|
||||
.resize({ width, withoutEnlargement: true })
|
||||
.webp({ quality: WEBP_QUALITY })
|
||||
|
||||
@@ -21,6 +21,12 @@ const UPLOAD_MIME: Record<string, string> = {
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.avif': 'image/avif',
|
||||
'.bmp': 'image/bmp',
|
||||
'.tif': 'image/tiff',
|
||||
'.tiff': 'image/tiff',
|
||||
'.heic': 'image/heic',
|
||||
'.heif': 'image/heif',
|
||||
'.jxl': 'image/jxl',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.pdf': 'application/pdf',
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user