멈멈-토이프로젝트(next.js)2

커뮤니티 이미지 업로드하기 1-3

순9 2024. 9. 19. 21:09
728x90

이미지를 업로드 후

이미지 url 클라이언트 컴포넌트로 가져 오기

 

수바베이스 이미지 url 가져오기

export async function fetchStroageImg(url:string): Promise<string> {
  const { data } = supabase
  .storage
  .from('communityimg')
  .getPublicUrl(url)
  return data.publicUrl;
}

 

api route

const filePath = `write/${(file as File).name}`;
    const { data, error } = await supabase.storage
      .from("communityimg")
      .upload(filePath, file, {
        cacheControl: "3600",
        upsert: false,
      });

    const imgurl = await fetchStroageImg(filePath);

1. 이미지를 수파베이스 스토리지에 등록 후

2. 스토리지에서 이미지 경로 가져오기

 

클라이언트 컴포넌트

const [imageUrl, setImageUrl] = useState<string | null>(null);


 const handleimgSubmit = async () => {
      const formData = new FormData();
      formData.append("file", selectedFile);

      try {
        const response = await fetch("/api/community-api", {
          method: "POST",
          body: formData,
        });

        if (!response.ok) {
          throw new Error("이미지를 업로드 하지 못했습니다");
        }

        const data = await response.json();

        // 서버에서 받은 이미지 URL을 상태에 저장
        setImageUrl(data.url);
      } catch (error) {
        console.error("Error:", error);
      }
    };

1. 이미지를 라우트 경로로 보내기

2. 업로드 하지 못했으면 에러출력

3. 성공 했으면 비동기로 경로 가져 오기