六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 15|回复: 0

java+mysql中保存图片及显示上传的图片struts+hibernate

[复制链接]

升级  61.3%

726

主题

726

主题

726

主题

探花

Rank: 6Rank: 6

积分
2226
 楼主| 发表于 2013-2-7 17:04:12 | 显示全部楼层 |阅读模式
用Java做了一下在Mysql中上传及显示图片的测试,struts+hibernate
jsp页面
<html:form action="/department.do?method=AddImage" enctype="multipart/form-data"><table><tr><td>姓名</td><td><html:text property="name"></html:text></tr><tr><td>电话</td><td><html:text property="tel"></html:text></td></tr><tr><td><html:file property="image"></html:file></td></tr><tr><td colspan="2"><html:submit></html:submit></td></tr></table></html:form> 
actionForm代码
public class DepartmentForm extends ActionForm {/** Generated fields*//** tel property */private String tel;/** name property */private String name;private String id;private FormFile image;/** Generated Methods*/public String getId() {return id;}public void setId(String id) {this.id = id;}/** * Method validate* @param mapping* @param request* @return ActionErrors*/public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {// TODO Auto-generated method stubreturn null;}/** * Method reset* @param mapping* @param request* @throws UnsupportedEncodingException */public void reset(ActionMapping mapping, HttpServletRequest request){// TODO Auto-generated method stubtry{request.setCharacterEncoding("gb2312");}catch(Exception ex){}}/** * Returns the tel.* @return String*/public String getTel() {return tel;}/** * Set the tel.* @param tel The tel to set*/public void setTel(String tel) {this.tel = tel;}/** * Returns the name.* @return String*/public String getName() {return name;}/** * Set the name.* @param name The name to set*/public void setName(String name) {this.name = name;}public FormFile getImage() {return image;}public void setImage(FormFile image) {this.image = image;}} action中代码
public ActionForward AddImage(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response){try{//保存图片信息DepartmentForm departmentform = (DepartmentForm)form; Department department = new Department();InputStream inputStream = departmentform.getImage().getInputStream();department.setName(departmentform.getName());department.setTel(departmentform.getTel());department.setImage(Hibernate.createBlob(inputStream));DepartmentDAO departmentDao = new DepartmentDAO();departmentDao.save(department);//显示图片Department department2 = (Department)departmentDao.findByProperty("id", department.getId()).get(0);Blob imageblob = (Blob)department2.getImage() ;InputStream input = imageblob.getBinaryStream();byte [] image = new byte[input.available()];ServletOutputStream out = response.getOutputStream();int len = 0;while((len=input.read(image))!=-1){out.write(image,0,len);}out.flush();out.close();return null;}catch(Exception ex){ return null ;}} 
黑色头发  http://heisetoufa.iteye.com
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表