ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 8월 17일 목요일 TIL 회고록
    카테고리 없음 2023. 8. 18. 00:44

    스프링 이미지 업로드 API 수정


    기존에 사용했던 이미지 업로드 API를 AwsS3Service에서 만든 업로드 API를 사용해서 수정했다.

     

    BasicBoardServiceImpl.class

     // 이미지 업로드
      @Override
      public void upload(List<MultipartFile> multipartFiles, BasicBoard basicBoard)
          throws IOException {
    
        // 이미지를 담을 uploadImages 리스트 생성
        List<String> uploadImages = new ArrayList<>();
        // 이미지가 있는지 확인하는 imageExistCheck 선언
        boolean imageExistCheck = false;
        // 매개변수로 들어온 multipartFiles (이미지 파일들)을 반복문을 들린다.
        for (MultipartFile multipartFile : multipartFiles) {
          // 이미지 파일이 비어있지 않으면 imageExistCheck를 true로 변경
          if (!multipartFile.isEmpty()) {
            imageExistCheck = true;
          }
        }
    
        // imegeExistCheck가 true면, uploadImages에 awsS3Service.upload 메서드를 사용해 이미지를 담는다.
        if (imageExistCheck) {
          uploadImages = awsS3Service.upload(multipartFiles);
        }
    
        // uploadImages의 이미지들을 반복문을 돌려 boardImage에 저장한다.
        for (String imagePath : uploadImages) {
          BoardImage boardImage = new BoardImage(imagePath, basicBoard);
          boardImageRepository.save(boardImage);
        }
      }

     

    원래 boardImage 엔티티에 originalName, fileSize 필드를 선언했었는데, awsS3Service에 이미지를 업로드 시키는 메서드가

    파일 크기와 이름을 표시해주므로 두 필드를 주석처리 해주었다.

    @Getter
    @Entity
    @NoArgsConstructor(force = true, access = AccessLevel.PROTECTED)
    public class BoardImage {
    
      // AWS S3를 사용하므로 originalName, fileSize는 필요가 없어졌습니다. (AwsS3Service에서 해주므로)
    
      @Column(nullable = false)
      private final String imagePath;
      
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "IMAGE_ID")
      private Long Id;
    
    //  @Column(nullable = false)
    //  private String originalName;
    
    //  private Long fileSize;
    
      @ManyToOne
      @JoinColumn(name = "BOARD_ID")
      private Board board;
    
      @Builder
      public BoardImage(String imagePath, Board board) {
        this.imagePath = imagePath;
        this.board = board;
      }

     

    게시글을 삭제할 때 게시글에 올려져있던 이미지도 삭제해야하므로 이미지 삭제 메서드도 수정했다.

      // 보드 이미지 삭제
      @Override
      @Transactional
      public void deleteBoardImages(Long boardId) {
    
        List<BoardImage> getAllImages = boardImageRepository.findAllByBoardId(boardId);
        List<String> imagePaths = new ArrayList<>();
    
        for (BoardImage boardImage : getAllImages) {
          imagePaths.add(boardImage.getImagePath());
        }
    
        for (String imagePath : imagePaths) {
          awsS3Service.deleteFile(imagePath);
        }
    
        boardImageRepository.deleteAllByBoardId(boardId);
      }

    1. boardImageRepository.findAllByBoardId 기능을 사용해 보드 Id에 있던 이미지들을 List<BoardImage> getAllImages 리스트에 넣어준다.

    2. 이미지 주소를 사용해 이미지를 지울것이므로 String형 ArrayList인 ImagePaths 리스트를 만들었다.

    3. for문을 사용해 boardImege에 ImagePath(주소)를 imagePaths 리스트에 넣어준다.

    4. for문을 사용해 게시글의 주소를 awsS3Service.deleteFile을 사용해서 지운다.

    5. boardImageRepository.deleteAllByBoardId 를 사용해서 BoardImage의 id를 지운다.

     

    1) 실행 결과 (Postman 사용)

     

    이미지를 추가하고 게시글 작성을 했다.

     

    H2 Console

    이미지 아이디, 이미지 주소가 잘 나와있다.

     

    AWS S3

    이미지가 성공적으로 업로드 되었다.

     

    2) 실헹 결과 VS CODE (LIVE SERVER 사용)

    게시글 작성 버튼을 누른 후 제목과 내용, 이미지를 첨부한 후 작성 버튼을 눌렀다.

     

    H2 Console

    이미지가 정상적으로 업로드되었다.

     

    AWS S3

    마찬가지로 업로드가 정상적으로 되었다.

     

    게시글 상세 조회

    게시글 상세 조회 시 이미지가 정상적으로 출력된다.

     

    이제 여러가지 잡다한 오류들만 잡으면 거의 완성단계..?? 일지도.. 여러가지 기능들을 더 넣어보고 싶다 ㅋㅋㅋ..

Designed by Tistory.