티스토리 뷰

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 MVC와 Dispatcher Servlet  (0) 2018.07.19
Spring JDBC  (0) 2018.07.19
Spring Bean 생성 및 사용  (0) 2018.07.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함