써먹는 웹개발

[jsp] 이미지를 파일 스트림으로 읽어서 보여주기 본문

웹개발/Java & Jsp

[jsp] 이미지를 파일 스트림으로 읽어서 보여주기

kmhan 2018. 7. 2. 17:55


728x90
반응형

180721

파일경로 또는 파일명이 특수문자나 한글명으로 되어있으면 이미지가 안보이는데 해결방법

server.xml의 연결중인 port의 Connector 안에 URIEncoding="utf-8" 추가

ex) <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8082" protocol="HTTP/1.1" redirectPort="8443"/>

※ 권장하는 방법은 아닙니다.



======================================================================

180702


public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException ,IOException

 {
  String ItemID  = req.getParameter("id");
  ItemID = ItemID.toUpperCase();
      String ItemType  = req.getParameter("type");
      ItemType = ItemType.toUpperCase();

   File imgFile = new  File(이미지경로)      ;
   중략..
   
   FileInputStream ifo = new FileInputStream(imgFile);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   byte[] buf = new byte[1024];
   int readlength = 0;
   while( (readlength =ifo.read(buf)) != -1 )
   {
    baos.write(buf,0,readlength);
   }
   byte[] imgbuf = null;
   imgbuf = baos.toByteArray();
   baos.close();
   ifo.close();    
   
   int length = imgbuf.length;   
   OutputStream out = res.getOutputStream();    
   out.write(imgbuf , 0, length);

   out.close();   
  }
  catch(FileNotFoundException e)
  {
   
  }
  catch(IOException e)
  {
   
  }  

 }

 

 

위 페이지가 ImageViewer 라는 서블릿 클래스라고 하면

HTML 페이지에서는 이미지 태그에 넣으시면 이미지가 보여집니다.

는 저장하면 아래 소스가 안보여서 그냥 붙인 태그입니다

<img src="/servlet/ImageViewer?id=100&type=A>

 

링크 태그에 넣으시면 파일 다운 됩니다.

<a href="/servlet/ImageViewer?id=100&type=A>다운</a>



출처: http://notgivuphil.tistory.com/541 [[phil-story] Always Fighting]

728x90
반응형


Comments