Files
msgapp/src/app/components/UploadButton.tsx

36 lines
1.3 KiB
TypeScript
Raw Normal View History

"use client";
import { useState } from "react";
import { useToast } from "@/app/components/ui/ToastProvider";
export function UploadButton({ onUploaded, multiple = false }: { onUploaded: (url: string) => void; multiple?: boolean }) {
const { show } = useToast();
const [loading, setLoading] = useState(false);
async function onChange(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files ?? []);
if (files.length === 0) return;
try {
setLoading(true);
for (const f of files) {
const fd = new FormData();
fd.append("file", f);
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" }} multiple={multiple} />
</label>;
}