在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 { } }