티스토리 뷰
Maven으로 스프링 프로젝트를 개발하다가 src/main/webapp 경로에 보관된 이미지를 제공하는 API를 만들일이 있어서 경로를 얻는 방법을 적는다.
Controller에서 HttpServletRequest 객체를 파라미터로 받은 뒤, request.getServletContext().getRealPath(""); 를 이용하면된다.
위 호출로 나온 경로는 src/main/webapp 까지의 경로로, 만약 resources/image/img123.png 식으로 보관했다면,
@RestController
public class ImageController {
@Autowired
ImageService imageService;
@GetMapping(value = "/image/{imageName}.{extension}", produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getImage(
@PathVariable(name = "imageName") String imageName,
@PathVariable(name = "extension", required = false, defaultValue = "png") String extension,
HttpServletRequest request) throws IOException {
String imagePath = request.getServletContext().getRealPath("resources/image/" + imageName + "." + extension);
InputStream imageStream = new FileInputStream(imagePath);
byte[] imageByteArray = IOUtils.toByteArray(imageStream);
imageStream.close();
return imageByteArray;
}
}
위와 같은 방식으로 이미지의 경로를 찾아서 이미지를 보내는 API를 만들 수 있다.
참고
webapp 경로
http://egloos.zum.com/geneus/v/3436389
image API 만들기
http://www.baeldung.com/convert-input-stream-to-array-of-bytes
'프로그래밍 > Web' 카테고리의 다른 글
Spring Error Page (0) | 2018.08.09 |
---|---|
Spring REST API 이미지 또는 파일을 리턴하기 (4) | 2018.08.09 |
Spring controller에서 webapp 폴더 경로 찾기 (0) | 2018.08.02 |
Spring MVC와 Dispatcher Servlet (0) | 2018.07.19 |
Spring JDBC (0) | 2018.07.19 |
Spring Bean 생성 및 사용 (0) | 2018.07.19 |
댓글
공지사항
- Total
- 221,436
- Today
- 137
- Yesterday
- 53
링크
TAG
- thymeleaf cannot resolve
- nodejs
- Barycentric coordinates
- 클로저
- @Component
- @Autowired
- mybatis
- @Qualifier
- spring batch
- Closure
- Check point within polygon
- Bin
- npm
- thymeleaf 변수 인식
- unity
- @Bean
- MySQL
- Tasklet
- chunk
- JavaScript
- Linux
- Express
- spring
- Bean