jsp
首先给要提交的表单添加下面属性
enctype="multipart/form-data"
添加input控件(这里我用的是html标签)
<html:file property="photoFile"/>
效果等同下面代码
<input type="file" name="photoFile">
form
添加下面属性,类型为FormFile
private FormFile photoFile;
public FormFile getPhotoFile() {
return photoFile;
}
public void setPhotoFile(FormFile photoFile) {
this.photoFile = photoFile;
}
model
添加下面属性,类型为Blob
private Blob photoFile;
public Blob getPhotoFile() {
return photoFile;
}
public void setPhotoFile(Blob photoFile) {
this.photoFile = photoFile;
}
hibernate映射文件
添加对应属性,类型为java.sql.Blob
<property
name="photoFile"
type="java.sql.Blob"
column="photoFile"
insert="true"
length="200"
update="true"
not-null="false"/>
action
action进行数据处理
//拿到图片
FormFile file = personForm.getPhotoFile();
//图片转换成二进制
byte[] byteOfFile = file.getFileData();
//二进制转换成Blob
Blob blob = (Blob) Hibernate.createBlob(byteOfFile);
person.setPhotoFile(blob);
personForm为jsp传过来的表单
person为你的model对象
hibernate保存person即可进行保存
显示在jsp页面上
jsp代码:调用action里面的getImg(…)方法
<img src="/bysj/personForm.do?method=getImg">
action代码:用下面方法遍历所有得到的数据(我这里只拿了一个数据)即可,记得return null
try {
for (Person person : personList) {
Blob photo = person.getPhotoFile();
InputStream in = photo.getBinaryStream();
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}