springmvc 文件上传、下载、预览。以二进制形式存放到数据库。

数据库中的关于传入附件的字段我写了2个:一个存放内容accessory,一个存放文件的后缀filetype

[color=darkred]上传:[/color]首先需要2个必须的jar:
commons.io-1.4.0.jar
commons.fileupload-1.2.0.jar

[color=blue]XXX-servlet.xml[/color]中写入上传拦截:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolve">
<property name="maxUploadSize" value="100000" />
</bean>


[color=blue]jsp页面:[/color]
<form method="POST" action="提交地址" name="frm" enctype="multipart/form-data">
<input type="file" name="accessory"/><br>
<input type="submit" οnclick="return checkacc();"/><br>
</form>
<!--如果需要验证传入的文件的类型,可以通过js验证,我这个是在提交的时候验证的-->
<!--
function checkacc(){
var postfix = frm.accessory.value.substring(frm.accessory.value.lastIndexOf(".")+1); //获得选择的上传文件的后缀名的正则表达式
if(postfix!=""){
if(!(postfix == "jpg"||postfix == "pdf"))
{
alert('文件类型不正确,请选择.jpg或者.pdf文件 !');
document.getElementById('accessory').value="";
document.getElementById('accessory').focus();
return false;
}
}
}
-->

注:在以前用servlet写的文件上传,加入enctype="multipart/form-data"这个字段,会造成获取不到form内其他字段的值,但在springmvc中不会出现这个问题。


[color=blue]java Controller类:[/color]
public ModelAndView addSaleStock(HttpServletRequest request,HttpServletResponse response) throws Exception {
MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("accessory");
byte[] inputData = null;
String fileType="";
if(file!=null){
inputData = inputStream2Byte(file.getInputStream());
String s=file.getOriginalFilename();
fileType=s.substring(s.lastIndexOf(".")+1);
}
//数据库中表的对象类(model),通俗说就是hibernate中的po
ValidRegstock validRegstock = new ValidRegstock();
validRegstock.setInputData(inputData);
validRegstock.setFiletype(fileType);
try {
//去看service类
this.getBeanOfValidRegstockService().addSendRegStock(validRegstock);
msg = "添加成功!";
} catch (Exception e) {
e.printStackTrace();
msg = "添加失败!";
}
return new ModelAndView(返回地址);
}


[color=blue]java service类:[/color]
public void addSendRegStock(ValidRegstock validRegstock)
throws Exception {
//去看dao类
regStockDao.add(validRegstock);
}


[color=blue]java dao类:[/color]
public void add(ValidRegstock validRegstock) {
String sql="insert into Z_ValidRegstock(accessory,filetype) values(?,?)";
//这里我们用数据连接的形式存入数据库
Connection conn=null;
try {
conn = getJdbcTemplate().getDataSource().getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
//注意 :大对象类型的 我们存入的是bytes[],这里要set object
ps.setObject(1, validRegstock.getInputData());
ps.setString(2, validRegstock.getFiletype());
ps.executeUpdate();
conn.commit();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

这样就能上传了。需要注意的是:

[color=olive]有些朋友会用:
Object[] params={validRegstock.getInputData()};
int[] dataTypes={Types.XXX};
getJdbcTemplate().update( sql, params, dataTypes);
这种方法存入,这里我之所以用了Types.XXX是因为 我试过Types.blob,Types.other等等都不好使。并且我把bytes[]用hibernate转为java.sql.blob的存入的话 也是不好使的。会出现类型不匹配java.oracle.blob.所以有用这种方法成功的朋友请告诉我。谢谢[/color]

[color=darkred]预览和下载差不多。同一个service,同一个dao,我先给出dao和service:[/color]
[color=blue]java dao类:[/color]
public List accessorySel(String id){
StringBuffer sql=new StringBuffer("");
sql.append("select accessory,filetype from Z_ValidRegstock where regstockId='");
sql.append(id);
sql.append("'");
Connection conn=null;
statement state=null;
ResultSet rs = null;
List list=new ArrayList();
try {
conn=getJdbcTemplate().getDataSource().getConnection();
state=conn.createStatement();
rs=state.executeQuery(sql.toString());
if (rs.next()) {
//这个blob是java.sql.Blob类型的
Blob blob = rs.getBlob("accessory");
String filetype=rs.getString("filetype");
list.add(0, blob);
list.add(1,filetype);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}


[color=blue]java service类:[/color]
public List accessorySel(String id){
return regStockDao.accessorySel(id);
}


[color=blue]java Controller类:[/color]
[color=indigo]预览:[/color]
public ModelAndView getAccessoryView(HttpServletRequest request,HttpServletResponse response) throws Exception {
String id=request.getParameter("id");
List list=this.getBeanOfValidRegstockService().accessorySel(id);
Blob blob=(Blob) list.get(0);
String filetype=(String) list.get(1);
int length = (int) blob.length();
byte[] bImage = new byte[length];
InputStream is = new BufferedInputStream(blob.getBinaryStream());
is.read(bImage, 0, length);
OutputStream out = response.getOutputStream();
out.write(bImage);
out.flush();
out.close();
is.close();
return null;
}


[color=indigo]下载:[/color]
public ModelAndView getAccessoryDownload(HttpServletRequest request,HttpServletResponse response) throws Exception {
//jsp传过来的 要下载附件对应数据的id
String id=request.getParameter("id");
List list=this.getBeanOfValidRegstockService().accessorySel(id);
Blob blob=(Blob) list.get(0);
String filetype=(String) list.get(1);
OutputStream fos = response.getOutputStream();
InputStream is = new BufferedInputStream(blob.getBinaryStream());
//如果下载的是表格形式的,可能会出现乱码。加入下面这句话:(其他出现乱码的情况自己百度下。)
response.setHeader("Content-Type","application/vnd.ms-excel");
//弹出保存框的语句,后面可以填入默认名称和类型
response.setHeader("Content-Disposition","Attachment;filename=accessory."+filetype);
byte[] buffer = new byte[1024];
int size = 0;
while ((size = is.read(buffer)) != -1) {
fos.write(buffer, 0, size);
}
fos.flush();
fos.close();
return null;
}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值