import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons"; import { Alert, App, Button, Image, Popconfirm, Spin, Upload } from "antd"; import { useEffect, useMemo, useState } from "react"; import { apiBaseUrl, authenticatedFetch, 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 { message } = App.useApp(); 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 authenticatedFetch(uploadUrl, { method: "PUT", headers: { "content-type": file.type }, 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 (
{uploading ?
{uploading ? "上传中..." : "点击或拖拽上传图片"}
JPG、PNG、WebP 或 AVIF,最大 10MB