feat: 接入对象存储图片直传
This commit is contained in:
1 parent
f57c0ca0ea
commit
84956b8fe2
14 files changed
+548
-15
No files matched your search
@@ -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
|
||||
|
||||
Reference in new issue
Block a user