uploadfile模块-上传和查看功能代码

上传:
控制层

SmartUpload su = new SmartUpload();
su.initialize(this.getServletConfig(), request, response);
try {
su.upload();//不要忘记写哦
manager.upload(su);
} catch (SmartUploadException e) {
e.printStackTrace();
}

smartupload还是很牛的。
业务层


File1 file = files.getFile(i);

//生成上传文件的实例
Uploadfiles fileInstance = new Uploadfiles();
fileInstance.setFilename(file.getFileName());
fileInstance.setFiletitle(su.getRequest().getParameter("title"));
fileInstance.setFilesize((long)file.getSize());
fileInstance.setFileext(file.getFileExt());
fileInstance.setCreatedate(new Date());
fileInstance.setContenttype(file.getContentType());

byte[] bytes = new byte[file.getSize()];

for(int j = 0 ; j < file.getSize() ; j++){
bytes[j] = file.getBinaryData(j);
}

//将大数据字段保存到另外一个表中,等需要的时候 再进行调用
//生成filecontent实例,并建立双向关联关系
Blob filecontent = Hibernate.createBlob(bytes);
Filecontent content = new Filecontent();
content.setUploadfiles(fileInstance);
content.setContent(filecontent);
fileInstance.getFilecontents().add(content);

//保存数据
try{
HibernateUtils.beginTransaction();
dao.saveFile(fileInstance);
HibernateUtils.commitTransaction();
}catch(Exception e){
HibernateUtils.rollbackTransaction();
e.printStackTrace();
}finally{
HibernateUtils.closeSession();
}
}


看到大牛们写的上传BLOB数据的方法有很多种,其中一种使用数量最多的是用游标来控制的,我偷懒直接用Hibernate的特性来。

展现:(起初最难控制的地方)
控制层:

String id = request.getParameter("id");

List list = manager.getContent(id);
byte[] bytes = (byte[])list.get(0);

//原来为了得到文件的类型,开始准备手工写type,最后发现FILE1类里面已经有了,差点走弯路。
response.setContentType(list.get(1).toString());
OutputStream outs = response.getOutputStream();
outs.write(bytes);
outs.flush();
outs.close();

业务层:

InputStream stream = null;

List list = new ArrayList();

Uploadfiles uf = getFileByID(new Long(id));

byte[] bytes = new byte[uf.getFilesize().intValue()];
try {
stream = uf.getFilecontents().iterator().next().getContent().getBinaryStream();

//还是有缺陷 long to int
stream.read(bytes);
list.add(bytes);
list.add(uf.getContenttype());
} catch (Exception e) {
e.printStackTrace();
}
return list;


总结:整体来说主要就是这些代码,完成了其中的上传和查看功能,smartupload里面的类其实不是很多,但是看起来还是有点难度,我只看完了里面的成员方法和变量,里面最牛的还是smartupload的getrequest()方法和File1的getContent()方法。我觉得那两个方法用好了,就可以了。还有就是性能上的问题,在查找资料的时候,看到从数据库抓取文件数据的时候,在没用到blob这个属性的时候还是不要抓出来了,尤其在列表的时候,我在hibernate里面设置了lazy。

本来想写一个上传多个文件的例子,结果偷懒之写完了单个文件上传的,最近在学struts,剩下的多个上传还是等闲了在写。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值