s3을 만들면서 MultipartFile을 받지 않아도 post를 만들 수 있도록 controller에 "required = false" 옵션도 줬는데 아래와 같은 오류가 났다.
2023-08-28T01:32:26.027+09:00 ERROR 19376 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "java.util.List.iterator()" because "files" is null] with root cause
for (MultipartFile file : files) {
if (file != null) {
String fileUrl = imageService.upload(file, "post " + post.getId());
if (imageRepository.existsByImageUrlAndId(fileUrl, post.getId())) {
throw new BusinessException(ErrorCode.EXISTED_FILE);
}
imageRepository.save(new Image(post, fileUrl));
}
}
s3 upload 부분 로직 문제인가 해서 다른 블로그에 있는 내용대로 다 수정했는데도 동일한 오류가 났다. 오류 내용 검색하던 중 null 체크를 해줘야 한다는 부분이 있어 혹시 싶어 if/for문의 위치를 바꿔보니 해결됐다.
if (files != null) {
for (MultipartFile file : files) {
String fileUrl = imageService.upload(file, "post " + post.getId());
if (imageRepository.existsByImageUrlAndId(fileUrl, post.getId())) {
throw new BusinessException(ErrorCode.EXISTED_FILE);
}
imageRepository.save(new Image(post, fileUrl));
}
}
매개변수로 받은 이미지 파일이 리스트여서 files > file로 반복문을 돌리고 null 체크를 했는데 required = false 옵션이 들어간 매개변수는 file이 아닌 files 이니 null 체크를 하고 for문 돌리는 것이 맞았다.