ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 커뮤니티 이미지 업로드하기 1-2
    멈멈-토이프로젝트(next.js)2 2024. 9. 11. 15:01
    728x90

    1-1은 이미지가 등록 되는지 확인 차

    클라이언트 컴포넌트에서 테스트 해 보았음

    이미지 등록 되는 것 확인

     

    문제 사항

    클라이언트에서 비동기를 사용 하면 안됨

    api route 활용

     

    클라이언트 컴포넌트

     const [selectedFile, setSelectedFile] = useState<File | null>(null);
    
      const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files && event.target.files.length > 0) {
          setSelectedFile(event.target.files[0]);
        }
      };

    이미지 여부 확인

     

    useEffect(() => {
        console.log("Selected file: ", selectedFile); 
        if (!selectedFile) {
          // 파일이 선택되지 않았다면 아무 작업도 하지 않음
          return;
        }
        const handleimgSubmit = () => {
          const formData = new FormData();
          formData.append("file", selectedFile);
          console.log(formData.get('file'));
      
          fetch('/api/community-api', {
            method: 'POST',
            body: formData,
          })
            .then((response) => {
              if (!response.ok) {
                throw new Error("이미지를 업로드 하지 못했습니다");
              }
              return response.json();
            })
            .catch((error) => {
              console.error("Error:", error);
            });
        };
      
        handleimgSubmit();
      }, [selectedFile]);

    1. 의존성 배열의 값이 변화가 오면 함수를 실행

    2. fetch route 경로로 데이터를 보냄

     

    route

    import { NextResponse } from "next/server";
    import { supabase } from "@/lib/db";
    
    export async function POST(request: Request) {
        try {
            const formData = await request.formData();
            
            for (let [key, value] of formData.entries()) {
                console.log(`${key}:`, value);
            }
    
    
            const file = formData.get('file');
            
           
            if (!file) {
                // 파일이 없는 경우
                return NextResponse.json({ error: '파일이 존재하지 않습니다.' }, { status: 400 });
            }
            const filePath = `write/${(file as File).name}`;
            console.log((file as File).name);
            const { data, error } = await supabase
              .storage
              .from('communityimg')
              .upload(filePath, file, {
                cacheControl: '3600',
                upsert: false
              });
    
            if (error) {
                // 파일 업로드 오류
                console.error('파일 업로드 오류:', error.message);
                return NextResponse.json({ error: '파일 업로드에 실패했습니다.' }, { status: 500 });
            }
    
            if (data) {
                const avatarUrl = data.path; // 파일 업로드 경로를 저장
                return NextResponse.json({ message: '이미지 업로드 성공', url: avatarUrl });
            } else {
                return NextResponse.json({ error: '파일 업로드에 실패했습니다.' }, { status: 500 });
            }
        } catch (error) {
            // 서버 오류 처리
            console.error('서버 오류:', error);
            return NextResponse.json({ error: '서버 오류가 발생했습니다.' }, { status: 500 });
        }
    }

    1. for문으로 이미지의 정보가  오는지 확인

    2. .get으로 file을 변수에 담음

    3. 수파베이스의 스토리지에 이미지 등록

     

     

    에러

    - new row violates row-level security policy (정책 에러)

    - http://localhost:3000/api/community-api 500 (Internal Server Error)

     

    정책 에러로 인해 서버도 에러 남

    정책 해결 되면서 서버 에러도 해결 됨

Designed by Tistory.