feat: 接入对象存储图片直传

This commit is contained in:
que01 committed 2026-10-12 00:55:30 +08:00
1 parent f57c0ca0ea
commit 84956b8fe2
14 files changed
+548 -15

No files matched your search

+55 -2
View File
@@ -1,14 +1,51 @@
import { Image, Input, Space, Typography } from "antd";
import { InboxOutlined } from "@ant-design/icons";
import { Image, Input, Space, Typography, Upload, message } from "antd";
import { useState } from "react";
import { createApiClient } from "../lib/api.js";
interface ImageUrlFieldProps {
id?: string;
value?: string;
onChange?: (value: string) => void;
placeholder?: string;
scope?: "brand" | "offering" | "trust";
}
export function ImageUrlField({ id, value, onChange, placeholder }: ImageUrlFieldProps) {
export function ImageUrlField({ id, value, onChange, placeholder, scope }: ImageUrlFieldProps) {
const imageUrl = typeof value === "string" ? value.trim() : "";
const [uploading, setUploading] = useState(false);
const client = createApiClient();
async function upload(file: File) {
if (!file.type.startsWith("image/")) {
message.error("仅支持图片文件");
return;
}
if (file.size > 10 * 1024 * 1024) {
message.error("图片不能超过 10MB");
return;
}
setUploading(true);
try {
const presign = await client.createPresignedUpload({
fileName: file.name,
contentType: file.type,
...(scope ? { scope } : {}),
});
const response = await fetch(presign.uploadUrl, {
method: "PUT",
headers: { "content-type": file.type },
body: file,
});
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
onChange?.(presign.publicUrl);
} catch {
message.error("图片上传失败,请重试");
} finally {
setUploading(false);
}
}
return (
<Space direction="vertical" size={8} style={{ width: "100%" }}>
<Input
@@ -17,6 +54,22 @@ export function ImageUrlField({ id, value, onChange, placeholder }: ImageUrlFiel
onChange={(event) => onChange?.(event.target.value)}
placeholder={placeholder ?? "粘贴图片地址"}
/>
<Upload.Dragger
accept="image/*"
multiple={false}
showUploadList={false}
disabled={uploading}
beforeUpload={(file) => {
void upload(file);
return false;
}}
>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">{uploading ? "上传中..." : "点击或拖拽上传图片"}</p>
<p className="ant-upload-hint">JPG、PNG、WebP 或 AVIF,最大 10MB</p>
</Upload.Dragger>
{imageUrl ? (
<Space align="start">
<Image
+8 -4
View File
@@ -201,14 +201,18 @@ export function BrandPage() {
<Form.Item
name="avatarUrl"
label="头像图片地址"
help="粘贴一张可公开访问的图片地址。"
help="点击上传或粘贴一张可公开访问的图片地址。"
>
<ImageUrlField />
<ImageUrlField scope="brand" />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item name="coverUrl" label="品牌封面图片地址" help="建议使用横向图片。">
<ImageUrlField />
<Form.Item
name="coverUrl"
label="品牌封面图片地址"
help="点击上传,或粘贴一张横向图片地址。"
>
<ImageUrlField scope="brand" />
</Form.Item>
</Col>
</Row>
@@ -495,9 +495,9 @@ export function ServicesPage() {
<Form.Item
name="coverUrl"
label="封面图片地址"
help="填写图片地址;图片上传能力将在后续媒体管理中提供。"
help="点击上传,或粘贴服务/产品封面图片地址。"
>
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" />
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
</Form.Item>
<Form.Item
name="sortOrder"
@@ -396,7 +396,7 @@ export function TrustContentPage() {
label="配图地址"
help="粘贴一张可公开访问的图片地址,保存前会显示预览。"
>
<ImageUrlField placeholder="粘贴案例或经历配图地址" />
<ImageUrlField placeholder="粘贴案例或经历配图地址" scope="trust" />
</Form.Item>
<Form.Item name="isPublished" label="公开状态">
<Select
+3 -1
View File
@@ -8,7 +8,7 @@
"lint": "eslint .",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "tsx --test test/**/*.test.ts",
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs",
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
"clean": "rimraf dist",
"start": "node dist/main.js",
"db:generate": "prisma generate",
@@ -17,6 +17,8 @@
"db:seed": "tsx prisma/seed.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1149.0",
"@aws-sdk/s3-request-presigner": "^3.1149.0",
"@nestjs/common": "^11.0.11",
"@nestjs/core": "^11.0.11",
"@nestjs/platform-fastify": "^11.0.11",
+2
View File
@@ -13,6 +13,7 @@ import {
} from "./modules/public/public-workspace.controller.js";
import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js";
import { AdminConfigController } from "./modules/admin/admin-config.controller.js";
import { AdminUploadController } from "./modules/admin/admin-upload.controller.js";
import { PublicOfferingController } from "./modules/public/public-offering.controller.js";
import { PublicInquiryFormController } from "./modules/public/public-inquiry-form.controller.js";
import { CustomerInquirySubmissionController } from "./modules/customer/customer-inquiry-submission.controller.js";
@@ -61,6 +62,7 @@ export class HealthController {
AdminBookingController,
AdminConfigController,
AdminReleaseController,
AdminUploadController,
],
providers: [
PrismaService,
@@ -0,0 +1,97 @@
import { BadRequestException, Body, Controller, Get, Post, Req } from "@nestjs/common";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { createHash, randomUUID } from "node:crypto";
import type { FastifyRequest } from "fastify";
import { IsIn, IsOptional, IsString, MaxLength } from "class-validator";
import { AdminAccessService } from "../../admin-access.service.js";
export class PresignUploadDto {
@IsString()
@MaxLength(255)
fileName!: string;
@IsString()
@IsIn(["image/jpeg", "image/png", "image/webp", "image/avif"])
contentType!: string;
@IsOptional()
@IsString()
@MaxLength(64)
scope?: "brand" | "offering" | "trust";
}
class ObjectStorage {
private readonly client = new S3Client({
region: process.env.OBJECT_STORAGE_REGION || "us-east-1",
...(process.env.OBJECT_STORAGE_ENDPOINT
? { endpoint: process.env.OBJECT_STORAGE_ENDPOINT }
: {}),
forcePathStyle: Boolean(process.env.OBJECT_STORAGE_ENDPOINT),
credentials: {
accessKeyId: process.env.OBJECT_STORAGE_ACCESS_KEY || "",
secretAccessKey: process.env.OBJECT_STORAGE_SECRET_KEY || "",
},
});
private get bucket(): string {
const bucket = process.env.OBJECT_STORAGE_BUCKET;
if (!bucket) throw new BadRequestException("媒体上传尚未配置");
return bucket;
}
publicUrl(key: string): string {
const endpoint = process.env.OBJECT_STORAGE_PUBLIC_URL?.replace(/\/$/, "");
return endpoint ? `${endpoint}/${key}` : `/${key}`;
}
async presignPut(key: string, contentType: string): Promise<string> {
return getSignedUrl(
this.client,
new PutObjectCommand({ Bucket: this.bucket, Key: key, ContentType: contentType }),
{ expiresIn: 600 },
);
}
}
const allowedExtensions = new Map([
["image/jpeg", ".jpg"],
["image/png", ".png"],
["image/webp", ".webp"],
["image/avif", ".avif"],
]);
@Controller("admin/uploads")
export class AdminUploadController {
private readonly storage = new ObjectStorage();
constructor(private readonly access: AdminAccessService) {}
@Get("config")
config() {
const configured = Boolean(
process.env.OBJECT_STORAGE_BUCKET &&
process.env.OBJECT_STORAGE_ACCESS_KEY &&
process.env.OBJECT_STORAGE_SECRET_KEY,
);
return { configured };
}
@Post("presign")
async presign(@Req() request: FastifyRequest, @Body() body: PresignUploadDto) {
await this.access.requireBrand(request);
const extension = allowedExtensions.get(body.contentType);
if (!extension) throw new BadRequestException("仅支持 JPG、PNG、WebP 或 AVIF 图片");
const cleanName = body.fileName
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.slice(-64);
const digest = createHash("sha256")
.update(`${body.scope ?? "brand"}:${cleanName}:${randomUUID()}`)
.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) };
}
}
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
test("upload presign DTO rejects unsupported media type and oversized names", async () => {
const { PresignUploadDto } = await import("../dist/modules/admin/admin-upload.controller.js");
const validator = await import("class-validator");
const invalid = new PresignUploadDto();
invalid.fileName = "x".repeat(256);
invalid.contentType = "application/pdf";
const errors = await validator.validate(invalid);
assert.ok(errors.some((error) => error.property === "fileName"));
assert.ok(errors.some((error) => error.property === "contentType"));
const valid = new PresignUploadDto();
valid.fileName = "hero.jpg";
valid.contentType = "image/jpeg";
assert.deepEqual(await validator.validate(valid), []);
});