2011-02-04 141 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目錄下。