supabase storage 이미지 업로드

대분류
기능 구현
기록일자
2024/03/30 09:39
소분류
데이터베이스
일정 분류
1주차
const uploadFile = async (file: File) => { const filePath = `uploads/${uuidv4()}_${file.name}`; // 고유한 파일 경로 생성 const { data, error } = await supabase.storage .from('images') .upload(filePath, file); if (error) { console.error('파일 업로드 실패:', error); return null; } else { const url = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/${data.path}`; return url; } } // supabase에 데이터 저장 const handleSubmit = async () => { const userId = "223e4567-e89b-12d3-a456-426614174002"; const classId = uuidv4(); const imageUrls = []; for (const image of images) { const url = await uploadFile(image.file); if(url) { imageUrls.push(url); } } const { data, error } = await supabase .from('class') .insert([ { user_id: userId, class_id: classId, category: category, hashtag: subCategory, title: className, description: classContent, quantity: personnel, max_ppl: maxNumber, min_ppl: minNumber, price: price, location: address, detailLocation: detailAddress, date: null, time: selectedTime, totalTime: totalTime, image: imageUrls, //mainImage: mainImage, }, ]); if (error) { console.error('Supabase에 데이터 저장 중 오류 발생:', error); } else { console.log('데이터 저장 성공:', data); } }; const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => { if (event.target.files && event.target.files[0]) { if (images.length >= 5) { alert('최대 5개의 이미지만 추가할 수 있습니다.'); return; } const file = event.target.files[0]; const preview = URL.createObjectURL(file); setImages([...images, { file, preview }]); } }; // 이미지 맨 앞으로 이동하는 함수 (이 함수를 컴포넌트 안에 추가) const handleMoveToFront = (index:number) => { const selectedImage = images[index]; const remainingImages = images.filter((_, i) => i !== index); const newImages = [selectedImage, ...remainingImages]; setImages(newImages); };
TypeScript
복사