在Web开发中图片的读取和展示是一个很常见的功能,实现的过程大致也都一样(包括在各种框架中……)!接下来用流的方式来实现图片的展示
1、 创建Servlet,实现读取,请求方式使用get请求;
package com.senvn.servlet; import java.io.File; 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 ShowImageServlet extends HttpServlet { private static final String JPG="image/jpeg;charset=GB2312"; /** * get方法 */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 本地文件路径 String filePath = "D:"+File.separator+"temp"+File.separator+"test1.jpg"; File file = new File(filePath); // 获取输出流 OutputStream outputStream = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file); // 读数据 byte[] data = new byte[fileInputStream.available()]; fileInputStream.read(data); fileInputStream.close(); // 回写 response.setContentType(JPG); outputStream.write(data); outputStream.flush(); outputStream.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
2、 配置文件,web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Servlet</display-name> <servlet> <description>显示图片Servlet</description> <display-name>显示图片</display-name> <servlet-name>ShowImageServlet</servlet-name> <servlet-class>com.senvn.servlet.ShowImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowImageServlet</servlet-name> <url-pattern>/showImage.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
3、 页面展示
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'upload.jsp' starting page</title> </head> <body> <img alt="showImage" src="/Servlet/showImage.do"> </body> </html>
4、 直接访问jsp即可
路径截图: