Trouble_Shooting

multipartfile은 isEmpty()로 체크한다면서 자꾸 file is null이라서 isEmpty() 실행 못한다고 오류날 때 해결법

산타는 뽀미 2023. 6. 16. 12:33
@RequestMapping("/project/article/doModify")
@ResponseBody
public String doModify(MultipartFile file) throws IOException {

    if(!file.isEmpty() || file != null) {
        fileService.updateFile(file, "article", id, fileId);
    }

    return Util.jsReplace(Util.f("%d번 게시물을 수정하였습니다.",id), Util.f("detail?id=%d", id));
}

이미지 올릴수도 있고 안 올릴수도 있는 게시글 수정할 때 이렇게 짰는데 자꾸 

Cannot invoke "org.springframework.web.multipart.MultipartFile.isEmpty()" because "file" is null

이런 오류가 나는것임!! 인터넷 검색해봐도 multipartFile 타입은 isEmpty로 체크하는거 맞댔는데.. 암튼 그래서 뭐 file이 null이라서 isEmpty()를 실행할 수 없다고 하니 !file.isEmpty()랑 file != null이랑 자리 바꿔서 해봤는데도 안되고 심지어 갑자기 file에 노란줄 뜨면서 뭐 함수 위에다가 @suppress 어쩌구를 꼭 추가해야된다나? (저번에 다른 함수에서 시키는대로 해봤는데 오류나서 다시 지웠던 경험이 있음) 암튼 그래서 너무 답답했음

그래서 쁨벙이(chatGPT)한테 물어봤더니 저 ||를 &&로 바꾸래서

	@RequestMapping("/project/article/doModify")
	@ResponseBody
	public String doModify(MultipartFile file) throws IOException {
		
		if(file != null && !file.isEmpty()) {
			fileService.updateFile(file, "article", id, fileId);
		}
		
		return Util.jsReplace(Util.f("%d번 게시물을 수정하였습니다.",id), Util.f("detail?id=%d", id));
	}

그냥 이렇게 간단하게만 바꿨는데 해결됨.. 수정 기능도 잘 됨.. file도 뭐가 들어왔고 비어있지도 않은 상태에서만 파일을 수정하겠다는거 아님?내가 이전에 짠 코드는 file에 뭐가 들어왔거나 비어있지 않거나 둘중 하나만 만족해도 파일을 수정하겠다는 것임!! 그럼 내가 doModify 함수 실행할때 file이 null인 상태니까 앞에있는 조건은 불만족하고.. 그럼 뒤에 있는 조건을 만족한건가? 그래서 실행할라고 했는데 안된다는 건가? 아니 근데 file이 null이면 당연히 file.isEmpty()도 만족하는거 아닌가? 이해가 안되네!! 그리고 더 빡치는 점은 doWrite에서는 내가 처음에 짰던 코드대로 || 이렇게 썼는데 작동한다는 것임!!

	@RequestMapping("/project/article/doWrite")
	@ResponseBody
	public String doWrite(MultipartFile file) throws Exception {
		
		if(!file.isEmpty() || file != null) {
			fileService.saveFile(file, "article", id);
		}
		
		return Util.jsReplace(Util.f("%d번 게시물이 등록되었습니다.",id), Util.f("list?boardId=%d", boardId));
	}

왜 doWrite에서는 되고 doModify에서는 안되는걸까?? 정말 화난당!

일단 작성하는데 문제는 없어서 doWrite는 안 바꾸고 냅둘건데 나중에 문제 생기면 &&로 바꿔야지 모..

원래 코딩이란게 이렇게 왜 안되는지 왜 되는지도 모르고 그냥 하는건가? 몰겠당~~!!