2011-02-04 2 views
3

서블릿의 파일 시스템에서 이미지 파일을 어떻게 제공합니까?서블릿의 파일 시스템에서 정적 이미지 파일을 제공 하시겠습니까?

+1

응용 프로그램 서버 란 무엇입니까? 일부는 정적 콘텐츠를 게시 할 웹 응용 프로그램을 정의하는 깨끗한 방법을 제공합니다 (예 : weblogic : http://blogs.oracle.com/middleware/2010/06/publish_static_content_to_weblogic.html – RealHowTo

+1

및 Tomcat : http://stackoverflow.com/questions)./1502841/신뢰할 수있는 데이터 제공/2662603 # 2662603 내 사이트에서 – BalusC

답변

2

다음을 살펴보십시오. Example Depot: Returning an Image in a Servlet 링크가 끊어졌습니다. 뒤로 기계 아래에 삽입 복사 :

// This method is called by the servlet container to process a GET request. 
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 
    // Get the absolute path of the image 
    ServletContext sc = getServletContext(); 
    String filename = sc.getRealPath("image.gif"); 

    // Get the MIME type of the image 
    String mimeType = sc.getMimeType(filename); 
    if (mimeType == null) { 
     sc.log("Could not get MIME type of "+filename); 
     resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
     return; 
    } 

    // Set content type 
    resp.setContentType(mimeType); 

    // Set content size 
    File file = new File(filename); 
    resp.setContentLength((int)file.length()); 

    // Open the file and output streams 
    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); 
    } 
    in.close(); 
    out.close(); 
} 
+0

이 작동하지만 한 달에 약 1,500 만 회의 페이지 조회가 발생하므로 최적화가 필요합니다. – sadgas

+0

안녕하세요 aioobe, 귀하의 링크가 끊어졌습니다. 즉,이 답변이 모두 손실되었습니다. 용도. ': (' –

+0

Thanks Matt. 링크가 끊어졌을 때 저자에게 알릴 수있는 서비스가 있다면 좋을 것입니다. 흠, 링크 된 각 웹 페이지의 캐시를 추가하는 것은 어떻습니까? – aioobe

0

음이 이미지가 웹 애플리케이션 디렉토리 아래에 위치하지 않는 한 서블릿 스펙, 그것을 할 수있는 명확한 방법이없는 것이 유감의 종류입니다. 서블릿 컨테이너는 일반적으로이를 수행 할 수있는 독점적 인 방법을 권장하지 않습니다. 분명히 컨테이너가 파일을 제공하기 위해이 작업을 수행해야합니다. 왜이 기능이 노출되지 않습니까? 왜 HttpServletResponse.sendFile(File)일까요?

가장 좋은 방법은 symlinks를 만들어서 파일이 webapp 디렉토리 아래에 있도록하는 것입니다.

관련 문제