🌱JAVA

[Java] jar 파일 실행 시 외부 폴더 이미지 찾아서 내려주기

뉴발자 2024. 2. 15.
728x90

 

 

 

 

 

 

 

 

 

 

 

 

 

 

그림 1. Spring Boot

 

 

폴더 구조 생성

jar파일이 있는 폴더 아래에 이미지를 저장할 폴더를 생성해준다.

그림 2. 이미지 파일 폴더 생성

 

생성한 img 폴더 안에 원하는 이미지 파일을 넣어주면 된다.

 

폴더 안의 파일을 불러온 후 화면에 출력해주는 코드를 작성한다.

 

 

코드 작성

@Slf4j
@RestController
@CrossOrigin
@RequiredArgsConstructor
public class ImageController {

    @GetMapping("img/**")
    public ResponseEntity<byte[]> getInternalImage(HttpServletRequest request) throws IOException {
        log.info("[ImageController - GET, /img/**]");

        // 이미지 파일 풀네임 추출
        String imageName = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);

        Path imagePath = Paths.get("img/", imageName);
        Resource resource = new FileSystemResource(imagePath.toFile());

        // InputStream을 사용하여 byte 배열로 변환
        InputStream inputStream = resource.getInputStream();
        byte[] imageBytes = inputStream.readAllBytes();

        // 이미지 데이터와 Content-Type을 설정하여 ResponseEntity 반환
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG) // 이미지 타입에 따라 변경
                .body(imageBytes);
    }
}

 

path에 불러올 이미지의 풀네임을 같이 받아서 HttpServletRequest 라이브러리로 불러올 이미지 이름을 찾아낸다.

 

만약 profile.jpg 이미지 파일을 받아오고 싶다면 URL은 다음과 같다.

http://localhost:8080/img/profile.jpg
728x90

 

 

테스트

jar파일과 동일한 폴더 내의 img 폴더의 이미지를 불러와 보겠다.

 

간단하게 postman을 사용해서 응답을 받았다.

그림 3. 이미지 파일 호출 및 응답

 

 

응용 - 이미지 URL을 사용한 이미지 출력

jar 폴더 내부의 이미지 파일이 아닌 이미지 URL로 출력도 가능하다.

 

코드 작성

@Slf4j
@RestController
@CrossOrigin
@RequiredArgsConstructor
public class ImageController {

    @GetMapping("external/**")
    public ResponseEntity<InputStreamResource> getExternalImage(HttpServletRequest request) throws IOException {
        log.info("[ImageController - GET, /external/**]");

        String imageName = request.getRequestURI().substring(request.getRequestURI().indexOf("/", 1));

        String imagePath = "https://blog.kakaocdn.net/dn/QZkBI/btsEdY3BarA/oJ7ul0LkoP8nU47W6TrWA1/" + imageName;

        URL url = new URL(imagePath);

        URLConnection connection = url.openConnection();

        InputStream inputStream = connection.getInputStream();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);

        return ResponseEntity.ok().headers(headers).body(new InputStreamResource(inputStream));
    }
}

 

 

테스트

Postman을 사용해 아래의 주소로 요청을 보낸다.

http://localhost:8080/external/img.jpg

 

결과는 다음과 같다.

그림 4. URL을 사용해서 이미지 가져오기

 

 

 

 

 

 

 

 

 

 

728x90

댓글