Welcome 微信登录

首页 / 软件开发 / JAVA / 巧妙使用Spring对commons fileUpload的包装

巧妙使用Spring对commons fileUpload的包装2011-03-23hbcui1984以前简单使用过spring的文件上传,当时没深入研究,以为spring只能实现单个文件的上传,所以后来就又大致学了下commons fileupload组件。在最近的工作中,有同事提出,他在把commons fileupload组件集成到spring中时总是出错,然后我大致看了一下,发现是spring DispatcherServlet的缘故。然后google了一下,发现sping本身就包装了commons fileupload,并且很好用。

一、前台页面

我们的目标是要实现多文件上传,并且预先我并不知道客户要上传多少个文件。我们先写个jsp页面吧!要实现可以动态控制上传多少文件,基本代码如下:

<form method="post" action="./upload.do" enctype="multipart/form-data">
<div id="uploadDiv">
<input type="file" name="file1" />
</div>
<input type="button" value="继续上传" onclick="javascript:btn_click();">
<input type="hidden" id="fileCount" name="fileCount" value="1">
<input type="submit" value="上传" />
</form>

要实现动态控制上传文件个数,我们需要使用javascript了。

function btn_click()...{
var fileNo=Number(document.getElementById("fileCount").value)+1;
newDiv=document.createElement("div")
newDiv.id="divFile"+fileNo;
document.getElementById("uploadDiv").appendChild(newDiv)
document.getElementById("fileCount").value=fileNo;
newDiv.innerHTML="<input type="file" name="file"+fileNo+"">";
}

ok,现在我们的界面如下:

图1

二、后台实现

1.前台我们搞定了,现在考虑一下后台处理吧!我写了一个Command Bean,非常简单,如下:

public class FUploadBean ...{
private byte[] file;
public byte[] getFile() ...{
return file;
}
public void setFile(byte[] file) ...{
this.file = file;
}
}

在spring Web MVC模式中,必须定义一个Command对象,将其和Form表单绑定。这个command class需要在spring上下文中进行配置,可以作为controller的property进行配置。一会会在配置文件中看到相关配置。