ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 프로젝트의 이미지 업로드!
    엘리스트랙 2024. 1. 20. 23:21
    728x90

     

     

     

    게시판을 생성할 때 그래도 게시판의 특성을 살릴 수 있는 사진이라도 있으면 좋을 것 같아서 사진을 넣는 기능을 추가하고 싶었다.

     

    일단 이미지 엔티티를 새로 생성해 보드와 연결해 주었다.

    @Getter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @Entity
    @Table(name = "boardImage")
    public class BoardImage {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column(nullable = false)
        private String url;
    
        @OneToOne
        @JoinColumn(name = "BOARD_ID")
        private Board board;
    }

     

    그리고 컨트롤러에서 MultipartFile을 추가한 Dto를 서비스에 같이 넘겨줘 파일을 올릴 수 있게 해 줬다.

     

    public Board saveBoard(BoardDto boardDto, BoardImageUploadDto boardImageUploadDto){
    
        Board boardEntity = boardDto.toEntity();
        Board savedBoard = boardRepository.save(boardEntity);
    
        if (boardImageUploadDto.getFiles() != null && !boardImageUploadDto.getFiles().isEmpty()) {
            for (MultipartFile file : boardImageUploadDto.getFiles()) {
                UUID uuid = UUID.randomUUID();
                String imageFileName = uuid + "_" + file.getOriginalFilename();
    
                File destinationFile = new File(uploadFolder + imageFileName);
    
                try {
                    file.transferTo(destinationFile);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
    
               
                boardDto.addImageUrl(imageFileName);
    
                BoardImage image = BoardImage.builder()
                        .url(imageUrl)
                        .board(savedBoard)
                        .build();
    
                boardImageRepository.save(image);
                boardEntity.setBoardImage(image);
            }
        }
        // 모든 이미지 처리 후 Board 객체 저장
        Board result = boardRepository2.save(boardEntity);
        return result;
    }

     

     

    <form th:action="@{/boards/create}" method="post" enctype="multipart/form-data">

     

    HTML에선 multipart로 이미지 파일을 넘길 수 있게 했다.

     

     

    th:src="@{'/image/' + ${board.boardImage.url}}"

     

    그럼 이제 게시판들을 띄워주는 HTML에서 이미지를 불러오게 했는데 여기서 계속 오류가 발생했다.

    src 형식을 계속 바꿔봐도 이미지가 불러와지지 않았고 뭐가 오류인지 계속 찾아보았다.

     

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/image/**")
                    .addResourceLocations("file:폴더경로");
        }
    }

     

    Spring Boot는 기본적으로 "/static", "/public", "/resources", "/META-INF/resources" 이렇게 4개의 위치에 있는 정적 리소스를 자동으로 제공하기 때문에 추가로 config를 구현해 주어야 됐다.

     

     

     

     

     

     

     

    728x90
Designed by Tistory.