使用servlet从Web根文件夹外部的文件夹中检索图像 [英] Retrieve images from a folder outside web root folder using servlet

查看:168
本文介绍了使用servlet从Web根文件夹外部的文件夹中检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个上传图片的小型servlet,并能够以幻灯片形式在不同的页面中检索它们。

I'm trying to create a small servlet that uploads images and is able to retrieve them in a different page as a slideshow.

我能够保存它们位于WebApp文件夹之外,但在检索它们时,我需要将它们作为JSP的一部分,除了图像之外还将包含其他内容。目前,我正在使用BufferedImage和ImageIO类一次流式传输一个图像。

I'm able to save them outside the WebApp folder, but while retrieving them I need them to be a part of a JSP which will have other content, apart from the images. Currently, I'm using BufferedImage and ImageIO classes to stream the images one at a time.

BufferedImage image = ImageIO.read(new File("D:\\"+file.getName()));
ImageIO.write(image, "jpg", response.getOutputStream());

在代码前面检查文件是JPEG文件类型。

The file is checked to be a JPEG file type earlier in the code.

推荐答案

您需要了解HTTP和HTML的工作原理:

You need to understand how HTTP and HTML work:


  1. 浏览器要求提供HTML页面(第一次请求)

  2. 服务器发送回HTML(仅限HTML),包含3 < img src =.. 。/> 标签

  3. 浏览器发送请求以获取第一个图像的字节(第二个请求)

  4. 服务器发回第一个图像的字节

  5. 浏览器发送请求以获取第二个图像的字节(第三个请求)

  6. 服务器发回第二个图像的字节

  7. 浏览器发送请求以获取第三个图像的字节(第四个请求)

  8. 服务器发送回第三个图像的字节

  1. The browser asks for an HTML page (first request)
  2. The server sends back HTML (and HTML only), containing 3 <img src="..."/> tags
  3. The browser sends a request to get the bytes of the first image (second request)
  4. The server sends back the bytes of the first image
  5. The browser sends a request to get the bytes of the second image (third request)
  6. The server sends back the bytes of the second image
  7. The browser sends a request to get the bytes of the third image (fourth request)
  8. The server sends back the bytes of the third image

因此,您需要一个生成HTML页面的servlet或JSP,其中包含您的所有内容< img src =。 ../> 标签。每个标签应具有以下形式:

So, you need a servlet or JSP which generates the HTML page, containing all your <img src="..."/> tags. Each of this tag should have the following form:

<img src="imageServlet?imageId=564"/>

你需要第二个servlet,映射到 imageServlet ,它读取文件系统中 imageId 参数值标识的图像的字节,并将这些字节写入响应输出流。

And you need a second servlet, mapped to imageServlet, which reads the bytes of the image identified by the imageId parameter value from the file system, and write those bytes to the response output stream.

这篇关于使用servlet从Web根文件夹外部的文件夹中检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆