做web开发时很多时候需要在网页上显示一张图片,有些图片是在项目工程中,可以通过项目地址链接引用,但有时候我们也需要使用存放在本地磁盘或者服务器上的图片,这时候我们就需要用java去读取图片,并在网页展示了。
一、在项目中的action层读取图片流,并输出到客户响应流中
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ImageAction extends HttpServlet {
- private static final long serialVersionUID = -1L;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //读取本地图片输入流
- FileInputStream inputStream = new FileInputStream("D:/image/123.jpg");
- int i = inputStream.available();
- //byte数组用于存放图片字节数据
- byte[] buff = new byte[i];
- inputStream.read(buff);
- //记得关闭输入流
- inputStream.close();
- //设置发送到客户端的响应内容类型
- response.setContentType("image/*");
- OutputStream out = response.getOutputStream();
- out.write(buff);
- //关闭响应输出流
- out.close();
- }
- }
二、在web.xml中加入该servlet (我这里演示暂时用的servlet方式,如果用框架则直接忽略该操作)
- <servlet>
- <servlet-name>imageUrl</servlet-name>
- <servlet-class>com.action.ImageAction</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>imageUrl</servlet-name>
- <url-pattern>/imgurl</url-pattern>
- </servlet-mapping>
三、在网页中引用该图片地址 http://localhost:8080/Demo/imgurl
- <img src="http://localhost:8080/Demo/imgurl" alt="" />