实现功能是 用户本地浏览一个图片后(本来要用上传 为简单起见就制作本地测试) 功过Hibernate中向数据库插入图片 并在另一个页面把这个图片显示出来
index.jsp
<body>
<form name="frm" action="imgServlet" method="post">
<input type="file" name="path"/>
<input type="submit" value="提交">
</form>
</body>
一个简单的表单用于浏览图片
Img.java
public class Img implements java.io.Serializable {
// Fields
private Integer id;
private byte[] img;
......
}
Img.hbm.xml
<hibernate-mapping>
<class name="hib.Img" table="img" schema="dbo" >
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="img" type="binary">
<column name="img" not-null="true" />
</property>
</class>
</hibernate-mapping>
servlet中的处理方式 (web.xml 中 <url-pattern>/imgServlet</url-pattern> 对这个servlet的配置)
public void doPostt(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
//PrintWriter out2 = response.getWriter();
//servlet 中 out 对象只可取一次.
//如果要用与输出二进制数据 . 就必须用 OutputStream 对象.
OutputStream out = response.getOutputStream();
request.setCharacterEncoding("UTF-8");
String path = request.getParameter("path");
java.io.File file = new File(path);
InputStream inputStream = new FileInputStream(file);
byte[] buff= new byte[(int) file.length()];
inputStream.read(buff, 0, (int) file.length());
Img img = new Img();
img.setImg(buff);
Session session = HibernateSessionFactory.getSession();
session.save(img);
session.beginTransaction().commit();
String realPath = request.getSession().getServletContext().getRealPath("/");
System.out.println("realPath"+realPath);
System.out.println("path:"+path);
System.out.println("插入成功!!!");
try {
//将图片写入到输出流中
out.write(img.getImg());
} catch (Exception e) {
e.printStackTrace();
}
//request.getRequestDispatcher("show.jsp").forward(request, response);
response.sendRedirect("show.jsp");
out.flush();
out.close();
}
show.jsp
<body>
<img src="imgServlet"/>
</body>
通过提交就可以在 show.jsp看到用户提交的图片并且改图片保存到了数据库
作者:caoyinghui1986 发表于2008-6-6 14:52:00
原文链接