-
Spring Controller에서 이미지 타입으로 리턴JAVA 2022. 1. 24. 15:47반응형
SSL 인증서가 적용된 사이트에서 http 프로토콜 도메인의 이미지는 url 로 삽입이 불가하다. 이를 서버 컨트롤러 단에서 마치 내 사이트 안에 있는 이미지 처럼 표기하는 방법.
클라이언트 단에서는 아래와같이 간단히 표기
<div id="myImage" class="img-box" style="background-image:url('/getPicture/1234/abc');"></div>이미지를 조회하기 위한 각 변수를 path로 받아서 처리
import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpStatus; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @RequestMapping(value="/getPicture/{depth1}/{depth2}", method=RequestMethod.GET) @ResponseBody public void getPictureFromURL(@PathVariable("depth1") String imgid, @PathVariable("depth2") String imgno, HttpServletRequest request, HttpServletResponse response) throws IOException { String imgUrl = "http://myurl/imgid="+imgid+"&imgno="+imgno; FileInputStream fis = null; InputStream is = null; BufferedOutputStream outs = null; try { response.setContentType("image/jpg;charset=UTF-8"); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Pragma", "No-cache"); response.setHeader("Expires", "0"); URL url = new URL(imgUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(false); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); if(conn.getResponseCode() != HttpStatus.SC_OK) { log.error("Error occurred code =="+String.valueOf(conn.getResponseCode())); return ; } is = conn.getInputStream(); byte imageData[] = new byte[2048]; int bytesRead = -1; outs = new BufferedOutputStream(response.getOutputStream()); if ( is != null ){ while ((bytesRead = is.read(imageData)) != -1) { outs.write(imageData, 0, bytesRead); } outs.flush(); } } catch (Exception e) { log.error(e.getMessage()); } finally { if(fis != null ) fis.close(); if(is != null ) is.close(); if(outs != null ) outs.close(); } }반응형'JAVA' 카테고리의 다른 글
Mybatis < foreach > 요소로 동적 쿼리 작성 (0) 2022.12.14 이클립스 속도 개선 eclipse.ini / Preference (0) 2021.01.08 Spring 다국어 적용하기 (0) 2020.05.27 Spring DAO DTO 사용하기 (0) 2020.05.12