우선 도움을 준 두개의 사이트에 감사를 표한다.
1. ResponseBody로 자바 객체 반환
이 방법은 우선 <img src="">안의 src 속성을 매핑하는 컨트롤러를 만들어서 객체를 반환해주는 방법이다.
방법은 이러하다. 우선 html파일 안에는 아래의 예제처럼
<img src="/images/9235597889000.jpg" class="img-fluid" alt="Responsive image">
그대로 경로를 적어주면 된다. src="/images/[파일이름]" 이런식으로
그리고
@ResponseBody
@GetMapping("/images/{filename}")
public Resource showImage(@PathVariable String filename) throws MalformedURLException {
File file = new File("images/20221116/" + filename);
return new UrlResource("file:" + file.getAbsolutePath());
}
이런 식으로 매핑을 해주면 된다.
실제 파일 경로 MyFirstProject/images/20221116/9235597889000.jpg
@ResponseBody : 리턴값인 자바 객체를 http 응답 Body에 넣어서 보내준다.
@PathVariable : 위의 매핑에서 {filename} 에 해당하는 값을 변수로 가져온다.
메서드 반환 타입은 Resource 인터페이스를 지정해준다
File file = new File(String path);를 통해 객체를 생성해주고 .getAbsolutePath를 통해 절대 경로를 가져온다.
new UrlResource("file:[절대경로]); 객체를 return해주면 된다.
그리고 실행시키면 이미지가 출력된다!!
사실 핵심은 어떻게든
@ResponseBody로 new UrlResource("file:[절대경로]); 객체를 return해주는 것이다.
2.thymeleaf로 처음 로딩될때 넣어서 주기
<img th:src="@{이미지 경로}" />
<img th:src="@{/img/logo_small.png}" />
하지만 아래의 글을 참고해보면 static에서 불러오는 방식은 변동되는 동적 컨텐츠에 적용하기는 부적절 한 것 같다.
https://junhyunny.github.io/spring-boot/cannot-find-static-resource/
'SpringBoot > [SpringBoot]' 카테고리의 다른 글
[SpringBoot] 파일 다운로드의 두 가지 방법 (0) | 2022.11.24 |
---|---|
[SpringBoot] Thymeleaf 반복문 첫번째 요소만 다르게 하기 (0) | 2022.11.17 |
[SpringBoot] 로컬 파일 저장과 DB를 같이 트랜잭션 시키기 (0) | 2022.11.16 |
[SpringBoot] @Transactional 의도적 에러 발생시키기 (0) | 2022.11.16 |
[Interceptor] 인터셉터를 통한 로그인 체크 / 접근 관리 (0) | 2022.11.14 |