用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 stub
return null;
}
/**
* Method reset
* @param mapping
* @param request
* @throws UnsupportedEncodingException
*/
public void reset(ActionMapping mapping, HttpServletRequest request)
{
// TODO Auto-generated method stub
try
{
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 ;
}
}