34 lines
1.2 KiB
TypeScript
34 lines
1.2 KiB
TypeScript
|
|
"use client";
|
||
|
|
import { useState } from "react";
|
||
|
|
import { useToast } from "@/app/components/ui/ToastProvider";
|
||
|
|
|
||
|
|
export function UploadButton({ onUploaded }: { onUploaded: (url: string) => void }) {
|
||
|
|
const { show } = useToast();
|
||
|
|
const [loading, setLoading] = useState(false);
|
||
|
|
async function onChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||
|
|
const f = e.target.files?.[0];
|
||
|
|
if (!f) return;
|
||
|
|
const fd = new FormData();
|
||
|
|
fd.append("file", f);
|
||
|
|
try {
|
||
|
|
setLoading(true);
|
||
|
|
const r = await fetch("/api/uploads", { method: "POST", body: fd });
|
||
|
|
const data = await r.json();
|
||
|
|
if (!r.ok) throw new Error(JSON.stringify(data));
|
||
|
|
onUploaded(data.url);
|
||
|
|
show("업로드 완료");
|
||
|
|
} catch (e) {
|
||
|
|
show("업로드 실패");
|
||
|
|
} finally {
|
||
|
|
setLoading(false);
|
||
|
|
e.currentTarget.value = "";
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return <label style={{ display: "inline-block" }}>
|
||
|
|
<span style={{ padding: "6px 10px", border: "1px solid #ddd", borderRadius: 6, cursor: "pointer" }}>{loading ? "업로드 중..." : "이미지 업로드"}</span>
|
||
|
|
<input type="file" accept="image/*" onChange={onChange} style={{ display: "none" }} />
|
||
|
|
</label>;
|
||
|
|
}
|
||
|
|
|
||
|
|
|