这是我的标记,用于显示我加载的图像:
<div id="loadedImages" style="display: inline-block;">
<img alt="First image" src="" />
<img alt="Second image" src="" />
</div>
在servlet中我加载了像
这样的图像FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
List<FileItem> multiparts = servletFileUpload.parseRequest(request);
ImageHolder.setImage1(ImageIO.read(multiparts.get(0).getInputStream()));
ImageHolder.setImage2(ImageIO.read(multiparts.get(1).getInputStream()));
ImageHolder是一个简单的类,它包含两个静态字段BufferedImage
和getter / setter。
如何在页面上显示此图像以及src
中的内容?
答案 0 :(得分:1)
您需要定义一个Servlet
来加载图像并将其发送到输出流。您还可以使用请求参数指定要加载的图像:
<div id="loadedImages" style="display: inline-block;">
<c:url var="firstURL"
value="/ImageServlet?imageId=First.jpg" />
<img alt="First image" src="${firstURL}" />
<c:url var="secondURL"
value="/ImageServlet?imageId=Second.jpg" />
<img alt="Second image" src="${secondURL}" />
</div>
并定义Servlet
如下所示,以加载图像并将图像发送到客户端:
public class ImageServlet extends HttpServlet {
...
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String imageName = request.getParameter("imageId");
//Read image into byte array
byte[] data = ImageHolder.readImage(imageName);
//Write image into output stream
response.setContentType("image/jpeg");
response.getOutputStream().write(data);
}
}