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
@@ -5,6 +5,16 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Uploads are capped at 15 MB by the API; nginx's 1 MB default would reject
|
||||
# any real photo with a bare 413 before the request ever reached it.
|
||||
client_max_body_size 20m;
|
||||
|
||||
# The first request for a given /api/img width renders it on demand; an
|
||||
# 8000px source can take a while on a small VPS, and nginx's 60s default
|
||||
# turned that into a 504 — a card thumbnail that stayed broken until the
|
||||
# variant finished, while the original (/uploads) opened fine.
|
||||
proxy_read_timeout 180s;
|
||||
|
||||
# Docker's embedded DNS. Without re-resolving at request time, nginx caches the
|
||||
# api container's IP from startup and keeps returning 502 ("no live upstreams")
|
||||
# after the api container restarts with a new IP.
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
-->
|
||||
<div class="gallery-upload">
|
||||
<a-upload-dragger
|
||||
accept="image/*"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif,image/avif,image/bmp,image/tiff,image/heic,image/heif,image/svg+xml"
|
||||
multiple
|
||||
:show-upload-list="false"
|
||||
:custom-request="doUpload"
|
||||
@@ -29,7 +29,7 @@
|
||||
class="tile"
|
||||
:class="{ 'is-uploading': item.status === 'uploading' }"
|
||||
>
|
||||
<img :src="imageUrl(item.url, 400) ?? item.preview" alt="" />
|
||||
<img :src="imageUrl(item.url, 400) ?? item.preview" alt="" @error="fallback($event, item)" />
|
||||
|
||||
<div v-if="item.status === 'uploading'" class="tile__progress">
|
||||
<a-progress type="circle" :percent="item.percent" :size="40" :stroke-width="8" stroke-color="#fff" trail-color="rgba(255,255,255,.3)" :show-info="false" />
|
||||
@@ -196,6 +196,18 @@ function preview(item: Item) {
|
||||
previewVisible.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A resized preview is a bonus, not a requirement: when the variant endpoint
|
||||
* fails (for example while the server is still rendering a huge source image)
|
||||
* fall back to the stored original so the tile never shows a broken image.
|
||||
*/
|
||||
function fallback(e: Event, item: Item) {
|
||||
const img = e.target as HTMLImageElement;
|
||||
if (item.url && img.src !== new URL(item.url, window.location.origin).href) {
|
||||
img.src = item.url;
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
items.value.forEach((i) => i.preview && URL.revokeObjectURL(i.preview));
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
:file-list="fileList"
|
||||
list-type="picture-card"
|
||||
:max-count="1"
|
||||
accept="image/*"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif,image/avif,image/bmp,image/tiff,image/heic,image/heif,image/svg+xml"
|
||||
:custom-request="doUpload"
|
||||
:before-upload="beforeUpload"
|
||||
@remove="handleRemove"
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
// Checks and error wording shared by the image uploaders. The limits mirror
|
||||
// AdminUploadsService in apps/api.
|
||||
export const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
|
||||
// AdminUploadsService in apps/api: 15 MB, up to 8000×8000, every standard
|
||||
// image format (plus PDF for document slots).
|
||||
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
const IMAGE_TYPES = /^image\/(jpeg|png|gif|webp|svg\+xml)$/;
|
||||
const IMAGE_TYPES =
|
||||
/^image\/(jpeg|jpg|pjpeg|png|apng|gif|webp|svg\+xml|avif|bmp|x-ms-bmp|tiff|heic|heif|jxl)$/;
|
||||
|
||||
/** Same list by extension, for files the browser reports with an empty type. */
|
||||
const IMAGE_EXTS = /\.(jpe?g|png|apng|gif|webp|svg|avif|bmp|tiff?|heic|heif|jxl)$/i;
|
||||
|
||||
/** Null when the file may be uploaded, otherwise the message to show. */
|
||||
export function checkImageFile(file: File): string | null {
|
||||
if (!IMAGE_TYPES.test(file.type)) {
|
||||
return `«${file.name}» پشتیبانی نمیشود؛ فقط تصویر JPG، PNG، WebP، GIF یا SVG`;
|
||||
const known = file.type ? IMAGE_TYPES.test(file.type) : IMAGE_EXTS.test(file.name);
|
||||
if (!known) {
|
||||
return `«${file.name}» پشتیبانی نمیشود؛ تصویر JPG، PNG، WebP، GIF، SVG، AVIF، BMP، TIFF یا HEIC انتخاب کنید`;
|
||||
}
|
||||
if (file.size > MAX_UPLOAD_BYTES) {
|
||||
return `حجم «${file.name}» بیشتر از ۸ مگابایت است؛ فایل کوچکتری انتخاب کنید`;
|
||||
return `حجم «${file.name}» بیشتر از ۱۵ مگابایت است؛ فایل کوچکتری انتخاب کنید`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
|
||||
@@ -5,6 +5,16 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Uploads are capped at 15 MB by the API; nginx's 1 MB default would reject
|
||||
# any real photo with a bare 413 before the request ever reached it.
|
||||
client_max_body_size 20m;
|
||||
|
||||
# The first request for a given /api/img width renders it on demand; an
|
||||
# 8000px source can take a while on a small VPS, and nginx's 60s default
|
||||
# turned that into a 504 — a card thumbnail that stayed broken until the
|
||||
# variant finished, while the original (/uploads) opened fine.
|
||||
proxy_read_timeout 180s;
|
||||
|
||||
# Docker's embedded DNS. Without re-resolving at request time, nginx caches the
|
||||
# api container's IP from startup and keeps returning 502 ("no live upstreams")
|
||||
# after the api container restarts with a new IP.
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<input
|
||||
ref="input"
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,application/pdf"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif,image/avif,image/bmp,image/tiff,image/heic,image/heif,image/svg+xml,application/pdf"
|
||||
class="siu__input"
|
||||
@change="onPick"
|
||||
/>
|
||||
@@ -58,9 +58,12 @@ const error = ref<string | null>(null)
|
||||
const fileId = ref<string | null>(null)
|
||||
const preview = ref<string | null>(null)
|
||||
|
||||
/** 8 MB — the same ceiling the API enforces, checked here for a fast message. */
|
||||
const MAX_BYTES = 8 * 1024 * 1024
|
||||
const ACCEPTED = /^(image\/(jpeg|png|webp)|application\/pdf)$/
|
||||
/** 15 MB — the same ceiling the API enforces, checked here for a fast message. */
|
||||
const MAX_BYTES = 15 * 1024 * 1024
|
||||
const ACCEPTED =
|
||||
/^(image\/(jpeg|jpg|pjpeg|png|apng|gif|webp|svg\+xml|avif|bmp|x-ms-bmp|tiff|heic|heif|jxl)|application\/pdf)$/
|
||||
/** Same list by extension, for files the browser reports with an empty type. */
|
||||
const ACCEPTED_EXT = /\.(jpe?g|png|apng|gif|webp|svg|avif|bmp|tiff?|heic|heif|jxl|pdf)$/i
|
||||
|
||||
function failureText(e: unknown): string {
|
||||
if (e instanceof UnauthorizedError) return 'برای بارگذاری، دوباره وارد حساب شوید'
|
||||
@@ -79,7 +82,7 @@ async function onPick(event: Event) {
|
||||
|
||||
error.value = null
|
||||
|
||||
if (!ACCEPTED.test(file.type)) {
|
||||
if (!(file.type ? ACCEPTED.test(file.type) : ACCEPTED_EXT.test(file.name))) {
|
||||
error.value = 'این نوع فایل پشتیبانی نمیشود؛ فقط تصویر JPG، PNG، WebP یا PDF'
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user