东拼西凑,实现一个用hibernate访问oracle里BLOB字段,并通过springMVC来控制文件的上传,下载。
备忘如下
1、表stu
create table STU
(
ID NUMBER not null,--pk,应用sequence:WRM_S_STU
NAME VARCHAR2(200),
FILENAME VARCHAR2(200),
FILEDATA BLOB
)
2、在myeclipse9.0的数据库浏览里找到该表,使用hibernate反转想到,生成dimain对象和DAO。
3、修改domain对象
3.1注解ID字段,引用序列
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "WRM_S_STU")
@Column(name="ID", unique=true, nullable=false, precision=2, scale=0)
3.2修改filedata字段,为java.sql.Blob类型
3.3该表将在页面以数据网格形式展现,故filedata字段不需要序列化(不添加在做表格查询会报错)
导入import org.codehaus.jackson.annotate.JsonIgnoreProperties;
domain实体加注解@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","filedata"})
4增加DAO的方法,实现按文件名称模糊查询 public List<Stu> FindobjByNmae(Stu stu)
原merge方法实现对象的更新,不行,调试不通过,blob字段无法更新,重写更新对象的方法
public boolean update_stu1(Stu entity) throws IOException {
boolean opFlag = false;
try {
HibernateTemplate template = this.getHibernateTemplate();
Session session = template.getSessionFactory().openSession();
session.update(entity);
session.flush();
session.close();
return true;
} catch (RuntimeException re) {
log.error("update stu_entity failed", re);
throw re;
}
}
其余自动生成的方法均可使用,(未测试对BLOB字段进行查找,比较)
5、ApplicationContext.xml,加入
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size100MB -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
6、写服务接口(页该爱表的操作面对),并在服务实现类中实现
public interface WrmStuService {
//增加一条记录到数据库
public int AddStuByObj(Stu stu,HttpServletRequest request);
//查询全部记录
public List<Stu> GetAllStu();
//条件查询记录,按名称,模糊查询
public List<Stu> GetAllStuByObjNAMELIKE(Stu stu);
//精确查询一条记录
public Stu GetOneStuById(Stu stu);
//更新数据库一条记录
public int UpdateStuByObj(Stu stu,HttpServletRequest request);
//删除一条记录
public int DeleteStuById(Stu stu,HttpServletRequest request);
}
7、页面和控制器
7.1新增功能
<form id=form_add enctype="multipart/form-data">
<h3>新增物料属性集</h3>
<table border="0">
<tr>
<td>名</td>
<td><input type="text" name="name" size="20" value="" id="name"> </td>
<td><font color="#ff0000">*</font></td>
</tr>
<tr>
<td>文件</td>
<td><input type="file" name="imgFile" id="imgFile" size="28" /> </td>
<td><font color="#ff0000">*</font></td>
</tr>
</table>
<input type="submit" value="添加" id="subAdd">
<hr align=center width=350 color=#987cb9 size=1>
</form>
JS里path_url代码
submitHandler : function() { //submitHandler:当form在客户端校验成功之后会执行里面的代码,
var pathUrL = "<%=path %>/mcode/maintain_stu_add.html";
$.omMessageBox.confirm({
title:'确认新增',
content:'确认新增数据到数据库,你确定要这样做吗?',
onClose:function(v){
if(v)
{
$('#subAdd').omButton('disable'),//失效按钮,避免多次提交
$('#form_add').omAjaxSubmit({ target: '#output',
success: showResponseAdd ,
url : pathUrL
});
}
}//onClose
});
return false; // 阻止浏览器默认行为
}
控制器,拦截到url请求后新增方法
//转型为MultipartHttpRequest(重点的所在)
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得第1张图片(根据前台的name名称得到上传的文件)
MultipartFile imgFile1 = multipartRequest.getFile("imgFile");
Stu stu_obj = new Stu();
if(!(imgFile1.getOriginalFilename() ==null || "".equals(imgFile1.getOriginalFilename()))) {
String fileName = imgFile1.getOriginalFilename();
//获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
//对扩展名进行小写转换
ext = ext.toLowerCase();
Blob photo=Hibernate.createBlob(imgFile1.getInputStream());
stu_obj.setFiledata(photo);}
stu_obj.setName(stu.getName());
stu_obj.setFilename(imgFile1.getOriginalFilename());
is_success = wrmstuservice.AddStuByObj(stu_obj, request);
7.2查询和一般网格查询一直,不显示blob字段
7.3更新和新增方法类似,服务调用自己写的更新方法,不用merge方法
7.4删除,单击选中一条记录,记录ID号传递到后台删除
7.5下载:双击数据网格某一行记录,跳转到下载URL
onRowDblClick: function( rowIndex, rowData, event)
{
var url= "<%=path %>/mcode/maintain_stu_download.html?download_id="+rowData.id;
window.open(url);
},
控制器
@RequestMapping(value="maintain_stu_download")
@ResponseBody
public ModelAndView To_maintain_stu_download(
HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException
{
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
BufferedInputStream bis = null; //
BufferedOutputStream bos = null; //
//存放原记录
Stu stu_obj = new Stu();
Stu stu_old = new Stu();
String download_id = request.getParameter("download_id");
download_id = download_id.trim();
// 从数据库中取得一条记录
stu_obj.setId(new BigDecimal(download_id));
stu_old = wrmstuservice.GetOneStuById(stu_obj);
//被下载文件的长度
Blob blob=stu_old.getFiledata();//被下载文件的BLOB字段
InputStream in=blob.getBinaryStream();//
long fileLength = blob.length();//BLOB长度
String fileName = stu_old.getFilename();//数据库表单独字段存放文件上传时候的文件名
String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()); //通过文件名获取文件类型
ext = ext.toLowerCase(); //对扩展名进行小写转换
String contentType = ext; //响应的类容类型(待下载的文件类型)
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename=" + new String(stu_old.getFilename().getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(blob.getBinaryStream()); //
bos = new BufferedOutputStream(response.getOutputStream()); //
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
return null;
}