2011-12-24 2 views
26

내 하드 드라이브에 저장된 이미지를 서블릿에 제공하는 방법은 무엇입니까?
예 :
이미지에 경로 'Images/button.png'이 저장되어 있으며이를 file/button.png이라는 서블릿에 제공하고 싶습니다. (그것은 단지 PNG 파일 인 경우)서블릿에서 이미지 파일 출력

+0

'이미지/png'또는 다음 답변에서 언급 한대로 필요한 내용 유형의 중요성을 알고 계십니까? – Lion

답변

19
  • image/pngContent-Type 헤더를 설정
  • 쓰기 그것을 response.getOutputStream()
  • 에 디스크에서 파일을 읽을 /file URL 패턴에 서블릿을 매핑
  • 45

    다음은 작동 코드입니다.

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 
    
         ServletContext cntx= req.getServletContext(); 
         // Get the absolute path of the image 
         String filename = cntx.getRealPath("Images/button.png"); 
         // retrieve mimeType dynamically 
         String mime = cntx.getMimeType(filename); 
         if (mime == null) { 
         resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
         return; 
         } 
    
         resp.setContentType(mime); 
         File file = new File(filename); 
         resp.setContentLength((int)file.length()); 
    
         FileInputStream in = new FileInputStream(file); 
         OutputStream out = resp.getOutputStream(); 
    
         // Copy the contents of the file to the output stream 
         byte[] buf = new byte[1024]; 
         int count = 0; 
         while ((count = in.read(buf)) >= 0) { 
         out.write(buf, 0, count); 
         } 
        out.close(); 
        in.close(); 
    
    } 
    
    0

    다른 아주 간단한 방법이 있습니다.

    File file = new File("imageman.png"); 
    BufferedImage image = ImageIO.read(file); 
    ImageIO.write(image, "PNG", resp.getOutputStream()); 
    
    +1

    이미지를 불필요하게 'BufferedImage' 객체로 파싱하므로 매우 비효율적입니다. 이미지를 조작하고 싶지 않은 경우 (크기 조절, 자르기, 변형 등)이 단계는 필요하지 않습니다. 가장 빠른 방법은 이미지 입력에서 수정되지 않은 바이트를 응답 출력으로 스트리밍하는 것입니다. – BalusC