멈멈-토이프로젝트(next.js)2
커뮤니티 이미지 삭제
순9
2024. 9. 21. 12:24
728x90
api 라우트 사용
정책 설정
const handleDelete = () => {
const parts = imageUrl.split("/");
const lastParts = parts[parts.length - 1];
setImg(true);
fetch("/api/community-delete-api", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ lastParts: lastParts }),
})
.then((response) => {
if (!response.ok) {
throw new Error("이미지 삭제 못 했습니다.");
}
return response.json();
})
.then((data) => {
console.log(data.message); // 서버에서 보낸 메시지
setImageUrl("");
// router.push('/main/diary');
})
.catch((error) => {
console.error("Error:", error);
});
};
1. 업로드 이미지의 주소를 가져와서 / 기준으로 나눈 후 마지막 요소 가져오기
2. 가져온요소 api로 보내기
export async function DELETE(request: Request) {
const { lastParts } = await request.json();
const encodedPath = `write/${lastParts}`;
try {
const { data, error } = await supabase.storage
.from("communityimg")
.remove([encodedPath]);
if (error) {
console.error("Supabase 에러:", error.message);
return NextResponse.json(
{ error: `이미지 삭제 실패: ${error.message}` },
{ status: 500 }
);
}
// console.log("삭제 성공:", data);
return NextResponse.json({ message: "이미지 삭제 성공" });
} catch (error) {
return NextResponse.json({ error: "이미지 삭제 못함" }, { status: 500 });
}
}
3. api로 마지막 요소 받은 후
4. 버킷과 폴더 경로 맞는지 확인 후 적용
handleDelete 실행되면
이미지 삭제
큰 에러는 없었음 이미지 업로드할때가 엄청 시간 걸렸음