Spring boot RestAPI 파일 다운로드

2023. 2. 10. 09:46·Java/Spring Boot

✅ Controller

로컬(서버)에서 가지고 있는 이미지를 클라이언트가 다운로드 받을 수 있도록 컨트롤러를 먼저 구현한다.

/**
 * 이미지 다운로드
 * @param elementId
 * @return
 */
@GetMapping("/imageDownload")
public ResponseEntity<Object> imageDownload(@RequestParam String elementId) {
    File file = new File("C:/Temp/ECM/" + elementId + ".tif");
    String path = "C:/Temp/ECM/";

	// 이 부분은 ECM 엔진에서 이미지를 다운로드 받는 별도의
    // 로직을 구현해뒀음
    if(file.exists()) {
        path = path + elementId + ".tif";
    } else {
        DownloadContent dc = new DownloadContent();
        String result = dc.download(elementId);
        path = path + result + ".tif";
        dc.discon();
    }

	// 이 부분이 다운로드 로직
    return service.imageDownload(path);
}

분기문에 들어가 있는 내용은 따로 작성해 둔 이미지를 다운로드 받는 로직이다.

이미지 혹은 파일을 꺼내기만 하면 되는 케이스라면 없어도 된다.

 

✅ ServiceImpl

@Override
public ResponseEntity<Object> imageDownload(String fileName) {
    try {
        Path filePath = Paths.get(fileName);
        Resource resource = new InputStreamResource(Files.newInputStream(filePath));

        File file = new File(fileName);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename(file.getName()).build());

        return new ResponseEntity<Object>(resource, headers, HttpStatus.OK);
    } catch(Exception e) {
        log.info("ImageServiceImpl 에러 내용, message={}", e.getMessage(), e);
        return new ResponseEntity<Object>(null, HttpStatus.CONFLICT);
    }
}

해당 부분이 실질적인 이미지 다운로드 로직이 되겠다.

 

참고로 예외를 Exception <- 이렇게 통으로 잡는 것은 좋지 않다!

저작자표시 비영리 (새창열림)

'Java > Spring Boot' 카테고리의 다른 글

Ajax를 통해 파일과 Json 업로드 후 Controller로 받기  (0) 2023.05.12
Spring boot Interceptor Ajax 체크 (Redirect 이슈)  (0) 2023.04.05
Spring boot Controller Zip 압축 해제  (0) 2023.01.25
Spring boot H2 DB 설정  (0) 2022.11.10
[Spring boot + React] Rest Api 연동하기  (0) 2022.08.16
'Java/Spring Boot' 카테고리의 다른 글
  • Ajax를 통해 파일과 Json 업로드 후 Controller로 받기
  • Spring boot Interceptor Ajax 체크 (Redirect 이슈)
  • Spring boot Controller Zip 압축 해제
  • Spring boot H2 DB 설정
요술공주밍키
요술공주밍키
조금씩이라도 꾸준히..
  • 요술공주밍키
    삽질의흔적
    요술공주밍키
  • 전체
    오늘
    어제
    • 분류 전체보기 (139)
      • Java (42)
        • Spring Boot (14)
        • Spring Boot 게시판 (14)
        • 공중화장실 찾기 (4)
        • 쇼핑몰 (8)
      • JavaScript (8)
        • NodeJS (2)
      • Python (5)
        • Django (4)
      • Server (10)
        • Docker (4)
        • K8S (0)
        • Jenkins (1)
      • 알고리즘 (24)
        • 프로그래머스 (19)
        • 백준 (5)
      • Etc (21)
        • 개발 팁 (1)
      • 일상 (27)
        • 독서 포스트 (25)
        • 회고록 (2)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
요술공주밍키
Spring boot RestAPI 파일 다운로드
상단으로

티스토리툴바