index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>文件上传页面测试</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="servlet/UpLoad" method="post" enctype="multipart/form-data"> <input type="file" name="uploadfile"> <input type="submit" name="submit" value="上传"> </form> </body> </html>
showpic.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*,javax.sql.*,javax.naming.*,java.io.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>显示数据库中的图片对象</title> </head> <body> 上传用户名:${requestScope.username }<br> <img src="ShowImage?picid=23" width="500px" height="600px"> <!-- 读取查询数据库中的图片对象 --> <%-- Context context=new InitialContext(); DataSource ds=(DataSource)context.lookup("java:/comp/env/jdbc/upload"); Connection con=ds.getConnection(); String sql="select pic_image from pic where pic_id=23"; PreparedStatement preparedStatement= con.prepareStatement(sql); ResultSet rs=preparedStatement.executeQuery(); //得到查询结果集 Blob picture=null; if(rs.next()){ picture=rs.getBlob(1); long size=picture.length(); //得到图片长度 byte [] bs=picture.getBytes(1,(int)size); OutputStream os=response.getOutputStream(); os.write(bs); //指定byte数组写入输出流 os.flush(); //刷新输出流,写出缓冲的输出字节 out.clear(); //JspWriter out = pageContext.pushBody(); //BodyContent is a subclass of JspWriter 返回一个空的out对象 //public BodyContent pushBody() //Return a new BodyContent object, save the current "out" JspWriter, //and update the value of the "out" attribute in the page scope attribute namespace of the PageContext //public abstract void clear()throws IOException //Clear the contents of the buffer. //If the buffer has been already been flushed //then the clear operation shall throw an IOException to signal the fact that //some data has already been irrevocably written to the client response stream }else{ out.println("没有找到图片"); } --%> </body> </html>
uploadDatabase.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>文件上传例题</title> <style type="text/css"> form{ margin-top:100px;} </style> </head> <body> 目录1:<%=request.getSession().getServletContext().getContextPath()%> 目录2:<%=request.getSession().getServletContext().getRealPath("/")%> <form action="servlet/UpLoadDatabase" method="post" enctype="multipart/form-data" name="form1" id="form1"> <table width="580" border="0" align="center" cellpadding="10" cellspacing="1" bgcolor="#999999"> <tr> <td bgcolor="#FFFFFF">网名:</td> <td colspan="2" bgcolor="#FFFFFF"><input name="username" type="text" id="username" /></td> </tr> <tr> <td bgcolor="#FFFFFF">文件:</td> <td colspan="2" bgcolor="#FFFFFF"><input type="file" name="file" /></td> </tr> <tr> <td bgcolor="#FFFFFF"> </td> <td bgcolor="#FFFFFF"><input name="submit" type="submit" id="submit" value="提交" /></td> <td bgcolor="#FFFFFF"><input name="reset" type="reset" id="reset" value="刷新" /></td> </tr> </table> </form> </body> </html>
package servlets; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.sql.*; import javax.naming.*; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.*; import javax.imageio.*; public class ShowImage extends HttpServlet { public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("图片查un:"+request.getParameter("picid")); //从客户端获取要查询的ID Integer picid=new Integer(request.getParameter("picid")); System.out.println("图片的ID"+picid); //数据库连接对象,方便finally使用 Connection con=null; //预处理命令对象 PreparedStatement ps=null; //结果集对象 ResultSet rs=null; try{ Context context=new InitialContext(); DataSource ds=(DataSource)context.lookup("java:comp/env/jdbc/upload"); //得到数据库连接对象 con=ds.getConnection(); String sql="select pic_image from pic where pic_id=?"; ps=con.prepareStatement(sql); //设置查询参数 ps.setInt(1,picid); //执行查询 rs=ps.executeQuery(); if(rs.next()){ response.setContentType("image/png"); Blob pic=rs.getBlob(1); System.out.println(pic); //得到向客户端响应的输出流 ServletOutputStream sos=response.getOutputStream(); //通过二进制大对象得到输入流 InputStream is=pic.getBinaryStream(); //通过ImageIO的静态方法得到BufferedImage BufferedImage image=ImageIO.read(is); System.out.println("图片"+pic); /* * 使用指定的png格式把(实现RenderedImage接口的BufferedImage) * image对象写入OutputStream 类型对象 */ ImageIO.write(image,"png",sos); //关闭输入流对象 is.close(); //刷新输出流,写出缓冲的输出字节 sos.flush(); sos.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ try { if(con!=null){ con.close(); } } catch (SQLException e) { e.printStackTrace(); }//关闭数据库连接try块 } } public void init() throws ServletException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
package servlets; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.*; public class UpLoad extends HttpServlet { public void destroy() { super.destroy(); // Just puts "destroy" string in log } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ DiskFileUpload fu=new DiskFileUpload(); PrintWriter out=response.getWriter(); //设置上传对象的字符编码和request一致 fu.setHeaderEncoding(request.getCharacterEncoding()); //限制上传文件大小 fu.setSizeMax(1024*1024*16); //设置临时保存解析占用内存空间大小 fu.setSizeThreshold(1024*1024*16); List fileItems=fu.parseRequest(request); Iterator it=fileItems.iterator(); FileItem fi=(FileItem)it.next(); //解析成fileItem String name=fi.getName(); //得到文件路径和名字 if(name.lastIndexOf("\\")!=-1){ //得到文件名去除路径名 String filename=name.substring(name.lastIndexOf("\\")); String webdir=request.getSession().getServletContext().getRealPath("/"); fi.write(new File(webdir+"uploadimage"+filename)); out.print("上传成功"); }else{ out.print("上传失败!"); } }catch(Exception e){ e.printStackTrace(); } } public void init() throws ServletException { } }
/** * 上传信息到数据库包括图片 */ package servlets; import java.io.*; import java.util.*; import java.sql.*; import javax.naming.*; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.*; import org.apache.commons.fileupload.*; /** * * */ public class UpLoadDatabase extends HttpServlet { private static final long serialVersionUID = 5220553409822159109L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileUpload df=new DiskFileUpload(); df.setHeaderEncoding(request.getCharacterEncoding()); df.setSizeMax(1024*1024*16); //设置文件最大为16M df.setSizeThreshold(1024*1024*3); //设置内存中缓冲3M if(df.isMultipartContent(request)){ InputStream is=null; PreparedStatement pst=null; Connection con=null; try { Map map=new HashMap(); List fileList=df.parseRequest(request); //解析请求到list集合 Iterator fileItems=fileList.iterator(); //迭代器 while(fileItems.hasNext()){ FileItem ft=(FileItem)fileItems.next(); if(ft.isFormField()){ //如果不是文件 map.put(ft.getFieldName(),ft.getString()); request.setAttribute(ft.getFieldName(),ft.getString()); }else{ map.put(ft.getFieldName(),ft); } }//遍历迭代器对象循环 FileItem file=(FileItem)map.get("file"); Context context = new InitialContext(); DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/upload"); con = ds.getConnection(); String inserta = "insert into pic (pic_name,pic_image) values (?,?)"; pst = con.prepareStatement(inserta); pst.setString(1, map.get("username").toString()); is = file.getInputStream(); //得到文件输入流 pst.setBinaryStream(2, is, (int)file.getSize()); int result = pst.executeUpdate(); //执行更新插入数据 if (result >= 1) { request.setAttribute("result", "上传文件成功!"); } else { request.setAttribute("result", "上传文件失败!"); }//判断是否上传成功块结束 } catch (Exception e) { System.out.println(new String(e.getMessage().getBytes("ISO-8859-1"),"GBK")); e.printStackTrace(); }finally{ try { pst.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } }else{ request.setAttribute("result","只能处理multipart/form-data类型的数据!"); return; }//判断是否是multipart/form-data类型数据块结束 //request.setAttribute("picid",23); System.out.println("目录1"+request.getSession().getServletContext().getContextPath()); System.out.println("目录2"+request.getSession().getServletContext().getRealPath("/")); RequestDispatcher td=request.getRequestDispatcher("../showpic.jsp?picid=23"); td.forward(request,response); } }
相关源代码