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

3

我该如何从servlet中提供文件系统中的图像文件?


1
你的应用服务器是什么?有些应用服务器提供了一种干净的方式来定义一个Web应用程序,以发布静态内容,例如Weblogic:http://blogs.oracle.com/middleware/2010/06/publish_static_content_to_weblogic.html - RealHowTo
1
还有Tomcat:http://stackoverflow.com/questions/1502841/reliable-data-serving/2662603#2662603 - BalusC
2个回答

2
请看这里:Example Depot: 在Servlet中返回图像 链接已经失效。以下是Wayback Machine的备份复制:

// 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();
}

适用于我的网站,但我们每月大约有1500万次页面浏览量,因此需要进行一些优化。 - sadgas
嘿aioobe,你的链接现在已经失效了,这意味着这个答案已经没有任何用处了。 :( - Matt Ball
谢谢Matt。如果SO有一个通知作者链接失效的服务,那就太好了。为什么不添加每个被链接网页的缓存呢? - aioobe

0

很遗憾,Servlet规范没有明确的方法来处理它,除非图像位于webapp目录下。 Servlet容器通常也不建议使用他们专有的方式来处理此问题。显然,容器必须这样做才能提供文件服务,为什么它不公开此功能呢?为什么不使用HttpServletResponse.sendFile(File)

您最好的选择是创建符号链接,以便您的文件出现在webapp目录下。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接