feat: 支持本地媒体存储与上传回退

This commit is contained in:
que01 committed 2026-10-12 01:39:56 +08:00
1 parent aa42e7b866
commit 6ac2d9421b
10 files changed
+256 -30

No files matched your search

@@ -0,0 +1,55 @@
import { BadRequestException, Controller, Put, Query, Req } from "@nestjs/common";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
const allowedExtensions = new Map([
["image/jpeg", ".jpg"],
["image/png", ".png"],
["image/webp", ".webp"],
["image/avif", ".avif"],
]);
@Controller("admin/uploads")
export class AdminLocalUploadController {
constructor(private readonly access: AdminAccessService) {}
private get mediaRoot(): string {
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media"));
}
@Put("local")
async upload(
@Req() request: FastifyRequest,
@Query("key") key?: string,
): Promise<{ saved: true }> {
await this.access.requireBrand(request);
const rawKey = key ?? (request.query as { key?: string }).key;
const decodedKey = (rawKey ?? "").includes("%")
? decodeURIComponent(rawKey as string)
: (rawKey ?? "");
if (
!decodedKey ||
decodedKey.includes("..") ||
decodedKey.startsWith("/") ||
!decodedKey.startsWith("media/")
) {
throw new BadRequestException("上传 key 无效");
}
if (!allowedExtensions.has(request.headers["content-type"] ?? "")) {
throw new BadRequestException("仅支持图片上传");
}
const contentType = allowedExtensions.get(request.headers["content-type"] ?? "");
if (!contentType || !decodedKey.endsWith(contentType)) {
throw new BadRequestException("上传文件类型与 key 不一致");
}
const target = path.join(this.mediaRoot, decodedKey);
if (!target.startsWith(path.resolve(this.mediaRoot))) {
throw new BadRequestException("上传 key 无效");
}
await mkdir(path.dirname(target), { recursive: true });
await writeFile(target, request.body as Buffer);
return { saved: true };
}
}
@@ -2,6 +2,8 @@ import { BadRequestException, Body, Controller, Get, Post, Req } from "@nestjs/c
import { HeadBucketCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { createHash, randomUUID } from "node:crypto";
import { mkdir } from "node:fs/promises";
import path from "node:path";
import type { FastifyRequest } from "fastify";
import { IsIn, IsOptional, IsString, MaxLength } from "class-validator";
import { AdminAccessService } from "../../admin-access.service.js";
@@ -45,6 +47,10 @@ class ObjectStorage {
return endpoint ? `${endpoint}/${key}` : `/${key}`;
}
get bucketName(): string {
return this.bucket;
}
async presignPut(key: string, contentType: string): Promise<string> {
return getSignedUrl(
this.client,
@@ -76,14 +82,32 @@ export class AdminUploadController {
constructor(private readonly access: AdminAccessService) {}
private get localMediaRoot(): string {
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media"));
}
private get localMediaBaseUrl(): string {
return process.env.LOCAL_MEDIA_BASE_URL || "/media";
}
@Get("config")
async config() {
const configured = Boolean(
const objectStorageConfigured = Boolean(
process.env.OBJECT_STORAGE_BUCKET &&
process.env.OBJECT_STORAGE_ACCESS_KEY &&
process.env.OBJECT_STORAGE_SECRET_KEY,
);
return { configured, status: configured ? await this.storage.checkBucket() : "unconfigured" };
const localMediaConfigured = Boolean(process.env.LOCAL_MEDIA_ROOT);
if (localMediaConfigured) {
return { configured: true, status: "ok", mode: "local" };
}
const configured = Boolean(objectStorageConfigured);
return {
configured,
status: configured ? await this.storage.checkBucket() : "unconfigured",
...(configured ? { bucket: this.storage.bucketName } : {}),
...(configured ? { mode: "object-storage" } : {}),
};
}
@Post("presign")
@@ -100,7 +124,22 @@ export class AdminUploadController {
.digest("hex")
.slice(0, 16);
const key = `media/${new Date().getFullYear()}/${digest}${extension}`;
const uploadUrl = await this.storage.presignPut(key, body.contentType);
return { uploadUrl, key, publicUrl: this.storage.publicUrl(key) };
const objectStorageEnabled = Boolean(
process.env.OBJECT_STORAGE_BUCKET &&
process.env.OBJECT_STORAGE_ACCESS_KEY &&
process.env.OBJECT_STORAGE_SECRET_KEY,
);
if (objectStorageEnabled) {
const uploadUrl = await this.storage.presignPut(key, body.contentType);
return { uploadUrl, key, publicUrl: this.storage.publicUrl(key) };
}
const target = path.join(this.localMediaRoot, key);
await mkdir(path.dirname(target), { recursive: true });
return {
uploadUrl: `/admin/uploads/local?key=${encodeURIComponent(key)}`,
key,
publicUrl: `${this.localMediaBaseUrl}/${key}`,
mode: "local",
};
}
}