这两天研究了一下图片存储在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+"/";
%>
显示图片
应下面网友要求,先将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";
}
}