我该如何从servlet中提供文件系统中的图像文件?
我该如何从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();
}
:(
- Matt Ball很遗憾,Servlet规范没有明确的方法来处理它,除非图像位于webapp目录下。 Servlet容器通常也不建议使用他们专有的方式来处理此问题。显然,容器必须这样做才能提供文件服务,为什么它不公开此功能呢?为什么不使用HttpServletResponse.sendFile(File)
?
您最好的选择是创建符号链接,以便您的文件出现在webapp目录下。