hibernate mysql 图片_Hibernate向数据库插入图片

实现功能是 用户本地浏览一个图片后(本来要用上传 为简单起见就制作本地测试) 功过Hibernate中向数据库插入图片 并在另一个页面把这个图片显示出来

index.jsp

一个简单的表单用于浏览图片

Img.java

public class Img  implements java.io.Serializable {

// Fields

private Integer id;

privatebyte[] img;

......

}

Img.hbm.xml

servlet中的处理方式   (web.xml 中 /imgServlet 对这个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

   imgServlet

通过提交就可以在 show.jsp看到用户提交的图片并且改图片保存到了数据库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值