728x90
폴더 구조 생성
jar파일이 있는 폴더 아래에 이미지를 저장할 폴더를 생성해준다.
생성한 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을 사용해서 응답을 받았다.
응용 - 이미지 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
결과는 다음과 같다.
728x90
'🛠️Backend > Spring' 카테고리의 다른 글
[Spring Boot] 프로젝트 실행 시 파일 존재 여부 확인 및 신규 파일 생성 (0) | 2024.03.06 |
---|---|
[Spring Boot] Launch4j과 jar 파일을 사용해서 실행 파일(.exe) 만들기 (0) | 2024.03.06 |
[Spring Boot] 단위 테스트 성공 시 Spring Rest Docs 파일 생성 (2) | 2024.01.02 |
[Spring Boot] 단위 테스트 코드 작성 (JUnit 5) (0) | 2024.01.02 |
[Spring Boot] 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 - 13 (0) | 2023.06.17 |
댓글