最好的方法是使用 servlet 并流回图像。流式处理是我们有一个 servlet,它正在读取服务器中的文件,并将字节发送回响应中。
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
String pathToWeb = getServletContext().getRealPath(File.separator);
File f = new File(pathToWeb + "avajavalogo.jpg");
BufferedImage bi = ImageIO.read(f);
OutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.close();
}
}
web.xml
。_
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="tomcat-demo" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>test.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
</web-app>
您的网址链接不起作用的原因是您可能没有在web.xml
文件中映射目录。最佳实践是使用像上面这样的单独 servlet 流回图像。也参考这个问题。