Files
persionalBrand/apps/admin/src/components/ImageUrlField.tsx
T

143 lines
4.7 KiB
TypeScript

import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react";
import { apiBaseUrl, 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, scope }: ImageUrlFieldProps) {
const imageUrl = typeof value === "string" ? value.trim() : "";
const [uploading, setUploading] = useState(false);
const [storageStatus, setStorageStatus] = useState<
"loading" | "ok" | "unavailable" | "unconfigured"
>("loading");
const client = useMemo(() => createApiClient(), []);
useEffect(() => {
let active = true;
client
.getUploadConfig()
.then((config) => {
if (active) setStorageStatus(config.configured ? config.status : "unconfigured");
})
.catch(() => {
if (active) setStorageStatus("unavailable");
});
return () => {
active = false;
};
}, [client]);
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 isLocalUpload = presign.mode === "local";
const uploadUrl = isLocalUpload
? `${apiBaseUrl.replace(/\/$/, "")}${presign.uploadUrl}`
: presign.uploadUrl;
const response = await fetch(uploadUrl, {
method: "PUT",
headers: {
"content-type": file.type,
...(isLocalUpload
? { authorization: `Bearer ${localStorage.getItem("adminToken") ?? ""}` }
: {}),
},
body: file,
});
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
onChange?.(presign.publicUrl);
} catch (error) {
message.error(error instanceof Error ? error.message : "图片上传失败,请重试");
} finally {
setUploading(false);
}
}
return (
<div className="admin-field-stack-xs admin-block">
{storageStatus !== "ok" ? (
<Alert
type={storageStatus === "loading" ? "info" : "warning"}
showIcon
message={
storageStatus === "loading"
? "正在检查媒体存储..."
: storageStatus === "unconfigured"
? "媒体存储未配置,请先设置对象存储"
: "媒体存储不可用,请检查对象存储配置"
}
/>
) : null}
{imageUrl ? (
<div className="admin-media-preview">
<Image
src={imageUrl}
alt={placeholder ?? "图片预览"}
width="100%"
height={180}
preview
fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
/>
<Popconfirm title="移除这张图片?" onConfirm={() => onChange?.("")}>
<Button danger size="small" icon={<DeleteOutlined />} className="admin-thumb-remove">
移除
</Button>
</Popconfirm>
</div>
) : (
<Upload.Dragger
accept="image/*"
multiple={false}
showUploadList={false}
disabled={uploading || storageStatus !== "ok"}
beforeUpload={(file) => {
if (storageStatus === "ok") void upload(file);
return false;
}}
>
<p className="ant-upload-drag-icon">{uploading ? <Spin /> : <PictureOutlined />}</p>
<p className="ant-upload-text">{uploading ? "上传中..." : "点击或拖拽上传图片"}</p>
<p className="ant-upload-hint">JPG、PNG、WebP 或 AVIF,最大 10MB</p>
</Upload.Dragger>
)}
{storageStatus === "unavailable" ? (
<Button
icon={<CloudUploadOutlined />}
onClick={() => {
setStorageStatus("loading");
client
.getUploadConfig()
.then((config) =>
setStorageStatus(config.configured ? config.status : "unconfigured"),
)
.catch(() => setStorageStatus("unavailable"));
}}
>
重新检查存储
</Button>
) : null}
<input {...(id ? { id } : {})} type="hidden" value={imageUrl} />
</div>
);
}