const handleImageUpload = (event) => {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
setImageSrc(reader.result);
setRecipeInfo({
...recipeInfo,
RECIPE_IMG: reader.result
});
};
}
};
미리보기에 사용한 base64 주소를 바로 DB에 보냈다
// 수정 페이지
if (path === "edit") {
let uploadedImageUrl = recipeInfo.RECIPE_IMG; // 기존 이미지 URL로 초기화
// 이미지가 변경된 경우에만 새 이미지를 업로드
if (fileInputRef.current.files.length > 0) {
const file = fileInputRef.current.files[0];
const fileName = `${Date.now()}_${file.name}`;
// supabase storage에 올리기
const { data, error } = await supabase.storage
.from("foodimg")
.upload(`images/${fileName}`, file);
if (error) {
console.error("이미지 업로드 중 오류 발생:", error.message);
return; // 이미지 업로드 실패 시, 더 이상 진행하지 않도록 종료
}
// 업로드한 주소 불러오기
uploadedImageUrl = supabase.storage.from("foodimg").getPublicUrl(`images/${fileName}`).data.publicUrl;
}
// 수정한 주소로 변경
await supabase
.from("recipe_info")
.upsert([{ ...recipeInfo, RECIPE_IMG: uploadedImageUrl }])
.eq("RECIPE_ID", editId);
// 작성 페이지
const file = fileInputRef.current.files[0];
const fileName = `${Date.now()}_${file.name}`;
const { data, error } = await supabase.storage
.from("foodimg")
.upload(`images/${fileName}`, file);
const uploadedImageUrl = supabase.storage.from("foodimg").getPublicUrl(`images/${fileName}`).data.publicUrl;
// recipe_info 테이블에 레시피 정보 삽입
const { data: recipeData } = await supabase
.from("recipe_info")
.insert([{ ...recipeInfo, RECIPE_IMG: uploadedImageUrl, USER_ID: id }])
.select();
거의 동일하고 수정페이지는 이미지 수정시에만 새 주소를 저장한다는 점과 upsert, insert 를 사용하는 부분이 다르다.
기존에 보내던 주소는 너무 길고 커서 로딩하는데에 오랜 시간이 걸렸었다. 주소를 변경해서 넣어주니 로딩이 아주 짧게 줄어들고 불러올 때 DB에 저장되어 있는 주소 길이도 짧아 보기에 편했다.