-
![]()
+
{{ fileExt(m) }}
diff --git a/apps/admin/src/views/ArtworkEdit.vue b/apps/admin/src/views/ArtworkEdit.vue
index 90534c4..90d961e 100644
--- a/apps/admin/src/views/ArtworkEdit.vue
+++ b/apps/admin/src/views/ArtworkEdit.vue
@@ -186,6 +186,7 @@
class="node-media-image"
:src="m.url"
:alt="m.name || n.title"
+ loading="lazy"
@click="previewNodeImage(n.media, m)"
/>
@@ -214,6 +215,7 @@
class="cert-preview-image"
:src="c.watermarkUrl || c.originUrl"
:alt="c.name"
+ loading="lazy"
@click="previewCert(c)"
/>
{{ t('pages.artwork.watermarkPending') }}
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index a641ff0..12b47da 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -10,6 +10,7 @@ import { AppModule } from './app.module';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
+import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service';
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
@@ -54,6 +55,13 @@ async function bootstrap(): Promise
{
}
app.useStaticAssets(localDir, {
prefix: config.get('storage.publicPrefix') || '/uploads',
+ etag: true,
+ lastModified: true,
+ maxAge: '1y',
+ immutable: true,
+ setHeaders: (res) => {
+ res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
+ },
});
// Swagger(开发文档)
diff --git a/apps/api/src/storage/local.driver.ts b/apps/api/src/storage/local.driver.ts
new file mode 100644
index 0000000..5610292
--- /dev/null
+++ b/apps/api/src/storage/local.driver.ts
@@ -0,0 +1,52 @@
+import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';
+import { dirname, relative, resolve } from 'path';
+import { PutOptions, StorageDriver } from './storage.types';
+
+export interface LocalDriverOptions {
+ localDir: string;
+ publicPrefix: string;
+ cdnBaseUrl: string;
+ baseUrl: string;
+}
+
+// 本地磁盘存储驱动(默认)。文件经 Nest 静态目录对外访问。
+export class LocalDriver implements StorageDriver {
+ private readonly root: string;
+
+ constructor(private readonly opts: LocalDriverOptions) {
+ this.root = resolve(opts.localDir);
+ }
+
+ private fullPath(key: string): string {
+ const full = resolve(this.root, key);
+ const rel = relative(this.root, full);
+ if (rel.startsWith('..') || rel === '' || rel.includes('..\\') || rel.includes('../')) {
+ throw new Error('Unsafe storage key');
+ }
+ return full;
+ }
+
+ async put(key: string, buffer: Buffer, _options?: PutOptions): Promise {
+ const full = this.fullPath(key);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, buffer);
+ }
+
+ async get(key: string): Promise {
+ return readFileSync(this.fullPath(key));
+ }
+
+ async remove(key: string): Promise {
+ const full = this.fullPath(key);
+ if (existsSync(full)) {
+ rmSync(full, { force: true });
+ }
+ }
+
+ getPublicUrl(key: string): string {
+ if (this.opts.cdnBaseUrl) {
+ return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
+ }
+ return `${this.opts.baseUrl.replace(/\/$/, '')}${this.opts.publicPrefix}/${key}`;
+ }
+}
diff --git a/apps/api/src/storage/oss.driver.ts b/apps/api/src/storage/oss.driver.ts
new file mode 100644
index 0000000..bdc83eb
--- /dev/null
+++ b/apps/api/src/storage/oss.driver.ts
@@ -0,0 +1,66 @@
+import {
+ DeleteObjectCommand,
+ GetObjectCommand,
+ PutObjectCommand,
+ S3Client,
+} from '@aws-sdk/client-s3';
+import { PutOptions, StorageDriver } from './storage.types';
+
+export interface OssDriverOptions {
+ endpoint: string;
+ region: string;
+ bucket: string;
+ accessKeyId: string;
+ accessKeySecret: string;
+ cdnBaseUrl: string;
+}
+
+// S3 兼容对象存储驱动(阿里云 OSS S3 兼容端点 / MinIO 等通用)。
+// 仅在 STORAGE_DRIVER=oss 时启用;凭据在 .env 配置,业务代码无需改动即可切换。
+export class OssDriver implements StorageDriver {
+ private readonly client: S3Client;
+
+ constructor(private readonly opts: OssDriverOptions) {
+ this.client = new S3Client({
+ region: opts.region || 'us-east-1',
+ endpoint: opts.endpoint || undefined,
+ forcePathStyle: true,
+ credentials: {
+ accessKeyId: opts.accessKeyId,
+ secretAccessKey: opts.accessKeySecret,
+ },
+ });
+ }
+
+ async put(key: string, buffer: Buffer, options?: PutOptions): Promise {
+ await this.client.send(
+ new PutObjectCommand({
+ Bucket: this.opts.bucket,
+ Key: key,
+ Body: buffer,
+ ContentType: options?.contentType,
+ CacheControl: options?.cacheControl,
+ }),
+ );
+ }
+
+ async get(key: string): Promise {
+ const res = await this.client.send(
+ new GetObjectCommand({ Bucket: this.opts.bucket, Key: key }),
+ );
+ const bytes = await res.Body!.transformToByteArray();
+ return Buffer.from(bytes);
+ }
+
+ async remove(key: string): Promise {
+ await this.client.send(new DeleteObjectCommand({ Bucket: this.opts.bucket, Key: key }));
+ }
+
+ getPublicUrl(key: string): string {
+ if (this.opts.cdnBaseUrl) {
+ return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
+ }
+ const base = (this.opts.endpoint || '').replace(/\/$/, '');
+ return `${base}/${this.opts.bucket}/${key}`;
+ }
+}
diff --git a/apps/api/src/storage/storage.module.ts b/apps/api/src/storage/storage.module.ts
new file mode 100644
index 0000000..8151be1
--- /dev/null
+++ b/apps/api/src/storage/storage.module.ts
@@ -0,0 +1,9 @@
+import { Global, Module } from '@nestjs/common';
+import { StorageService } from './storage.service';
+
+@Global()
+@Module({
+ providers: [StorageService],
+ exports: [StorageService],
+})
+export class StorageModule {}
diff --git a/apps/api/src/storage/storage.service.ts b/apps/api/src/storage/storage.service.ts
new file mode 100644
index 0000000..e946869
--- /dev/null
+++ b/apps/api/src/storage/storage.service.ts
@@ -0,0 +1,104 @@
+import { Injectable, Logger } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { createHash } from 'crypto';
+import dayjs from 'dayjs';
+import { nanoid } from 'nanoid';
+import { extname } from 'path';
+import { LocalDriver } from './local.driver';
+import { OssDriver } from './oss.driver';
+import { SavedFile, StorageDriver } from './storage.types';
+
+export const STATIC_ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';
+
+const MIME_EXT: Record = {
+ 'image/jpeg': '.jpg',
+ 'image/png': '.png',
+ 'image/webp': '.webp',
+ 'image/gif': '.gif',
+ 'image/svg+xml': '.svg',
+ 'video/mp4': '.mp4',
+ 'video/webm': '.webm',
+ 'video/quicktime': '.mov',
+ 'application/pdf': '.pdf',
+};
+
+@Injectable()
+export class StorageService {
+ private readonly logger = new Logger(StorageService.name);
+ private readonly driver: StorageDriver;
+
+ constructor(private readonly config: ConfigService) {
+ const s = this.config.get>('storage')!;
+ if (s.driver === 'oss') {
+ this.driver = new OssDriver({
+ endpoint: s.oss.endpoint,
+ region: s.oss.region,
+ bucket: s.oss.bucket,
+ accessKeyId: s.oss.accessKeyId,
+ accessKeySecret: s.oss.accessKeySecret,
+ cdnBaseUrl: s.cdnBaseUrl,
+ });
+ this.logger.log('存储驱动:OSS/S3 兼容');
+ } else {
+ this.driver = new LocalDriver({
+ localDir: s.localDir,
+ publicPrefix: s.publicPrefix,
+ cdnBaseUrl: s.cdnBaseUrl,
+ baseUrl: this.config.get('baseUrl') || 'http://localhost:3000',
+ });
+ this.logger.log('存储驱动:本地磁盘');
+ }
+ }
+
+ private buildHash(buffer: Buffer): string {
+ return createHash('sha256').update(buffer).digest('hex');
+ }
+
+ private buildKey(originalName: string, hash: string, mime?: string): string {
+ const ext = (mime && MIME_EXT[mime]) || extname(originalName) || '';
+ return `${dayjs().format('YYYY/MM/DD')}/${hash.slice(0, 16)}-${nanoid()}${ext}`;
+ }
+
+ async save(buffer: Buffer, originalName: string, mime?: string): Promise {
+ const hash = this.buildHash(buffer);
+ const key = this.buildKey(originalName, hash, mime);
+ await this.driver.put(key, buffer, {
+ contentType: mime,
+ cacheControl: STATIC_ASSET_CACHE_CONTROL,
+ });
+ return {
+ key,
+ url: this.driver.getPublicUrl(key),
+ name: originalName,
+ size: buffer.length,
+ mime: mime || 'application/octet-stream',
+ hash,
+ };
+ }
+
+ async putKey(key: string, buffer: Buffer, mime?: string): Promise {
+ await this.driver.put(key, buffer, {
+ contentType: mime,
+ cacheControl: STATIC_ASSET_CACHE_CONTROL,
+ });
+ return this.driver.getPublicUrl(key);
+ }
+
+ derivedKey(sourceKey: string, suffix: string): string {
+ const ext = extname(sourceKey);
+ const base = sourceKey.slice(0, sourceKey.length - ext.length);
+ return `${base}_${suffix}${ext || '.jpg'}`;
+ }
+
+ getUrl(key: string): string {
+ return this.driver.getPublicUrl(key);
+ }
+
+ read(key: string): Promise {
+ return this.driver.get(key);
+ }
+
+ async remove(key: string): Promise {
+ await this.driver.remove(key);
+ }
+}
diff --git a/apps/api/src/storage/storage.types.ts b/apps/api/src/storage/storage.types.ts
new file mode 100644
index 0000000..906c1ee
--- /dev/null
+++ b/apps/api/src/storage/storage.types.ts
@@ -0,0 +1,20 @@
+export interface PutOptions {
+ contentType?: string;
+ cacheControl?: string;
+}
+
+export interface StorageDriver {
+ put(key: string, buffer: Buffer, options?: PutOptions): Promise;
+ get(key: string): Promise;
+ remove(key: string): Promise;
+ getPublicUrl(key: string): string;
+}
+
+export interface SavedFile {
+ key: string;
+ url: string;
+ name: string;
+ size: number;
+ mime: string;
+ hash: string;
+}