hibernate mysql 图片_Struts2+Hibernate3将图片保存于mysql数据库并将其显示在JSP页面

这两天研究了一下图片存储在mysql数据库中,并显示在jsp页面上。

我创建的数据库只有一个表image(id int,image blob);

上传文件页面:upImages.jsp

上传照片

struts.xml文件:

/p>

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">

image/bmp,image/png,image/gif,image/jpg

40480

/upImages.jsp

http://www.baidu.com

http://www.baidu.com

/showPicture.jsp

显示图片页面:showPicture.jsp

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

显示图片

    %24%7Bsout%20%7D

应下面网友要求,先将action主要代码贴出来

public class MyUpAction extends ActionSupport{

private File upload = null;

private String uploadContentType;//文件类型,这两个属性,Struts2自动会解析

private String uploadFileName; //文件名

HttpServletResponse response = ServletActionContext.getResponse();

ServletOutputStream sout;//二进制流可以直接在jsp页面显示

public String execute(){

System.out.println(upload);

System.out.println(uploadContentType);

System.out.println(uploadFileName);

if(uploadFileName == null)

{

this.addFieldError("upload", "请选择文件");

System.out.println("sdfasdf");

}

else{

try{

Images img = new Images();

FileInputStream str=new FileInputStream(upload);

Blob photo = Hibernate.createBlob(str);

//img.setId(1);

img.setImage(photo);

ImagesDAO imagesDAO = new ImagesDAOImpl();

imagesDAO.save(img);

}catch(IOException e){

e.printStackTrace();

}

}

return SUCCESS;

}

public String getImage(){

ImagesDAO imagesDAO = new ImagesDAOImpl();

Images img = imagesDAO.findById(3);

Blob photo = img.getImage();

try {

InputStream in = photo.getBinaryStream();

sout = response.getOutputStream();

byte b[] = new byte[1024];

int len = in.read(b);

while(len!=-1){

sout.write(b);

len = in.read(b);

}

sout.flush();

sout.close();

in.close();

} catch (SQLException e) {

e.printStackTrace();

return "error";

}catch (IOException e){

e.printStackTrace();

return "error";

}

return "show";

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值