2011-02-04 71 views
3

如何从servlet在文件系统中提供图像文件?从servlet中的文件系统提供静态图像文件?

+1

什么是您的应用程序服务器?一些提供了一个干净的方式来定义一个Web应用程序发布静态内容,例如weblogic:http://blogs.oracle.com/middleware/2010/06/publish_static_content_to_weblogic.html – RealHowTo 2011-02-05 00:05:04

+1

和Tomcat:http://stackoverflow.com/questions/1502841/reliable-data-serving/2662603#2662603 – BalusC 2011-02-05 00:26:58

回答

2

看一看: Example Depot: Returning an Image in a Servlet 链接断了。 Wayback机器复制下面插入:

// 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

那么这是怎样的一个耻辱的是Servlet规范并没有明确的方式做到这一点,除非图像位于Web应用程序目录下。 Servlet容器通常不会建议他们专有的方法来做到这一点。显然,容器必须这样做才能提供文件,为什么它不公开功能?为什么不是HttpServletResponse.sendFile(File)

最好的办法是创建符号链接,以便您的文件显示在webapp目录下。