Struts多附件上传

动态的file输入域实现sturts的多文件上传,请大家看看还能不能优化??
这是jsp页面的代码:
js的作用主要是生成动态的file域
<script>
var i=0;
function addElements(){
with(document.forms("demo")){
if(i>=5){
alert("最多不能超过5个!");
return ;
}
insertAdjacentHTML("beforeEnd","<input type=/"file/" id="+i+" value="+i+" name=input"+(i++)+"> <br>" ) ;
}
}
function lastElement(){
with(document.forms("demo")){
insertAdjacentHTML("beforeEnd","<input type=/"hidden/" value="+(i)+" name=/"maxNum/" >") ;
}
}
</script>
下面是文件上传的form表单:
<form action="${pageContext.request.contextPath}/multiUpload.do"
name=demo method="post" enctype="multipart/form-data" onsubmit="lastElement();">
<input type="button" onclick=addElements(); value="增加" >
<input type="submit" name="save" value="Save" >
<br>
</form>


以上工作就可以完成动态的产生需要的file域了.
在看formBean:
public class MultiUploadForm extends ActionForm {
private FormFile file;
//多附件上传应该是一个数组
private List<FormFile> myFiles;
public MultiUploadForm(){
myFiles = new ArrayList<FormFile>();
//为了能够在页面初始显示一个file
myFiles.add(file);
}
public List<FormFile> getMyFiles() {
return myFiles;
}
public void setMyFiles(List<FormFile> myFiles) {
this.myFiles = myFiles;
}

public FormFile getFile() {
System.out.println("run in uploadFile.getFile()");
return file;
}
public void setFile(FormFile file) {
this.file = file;
}

}


然后就是action了:
public class MultiUploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {

MultiUploadForm multiUploadForm = (MultiUploadForm) form;
// 获取全部的文件上传资料:
MultipartRequestHandler mrh =multiUploadForm.getMultipartRequestHandl er();
Map formFiles = mrh.getFileElements();
// 实现文件上传的复制:
if (formFiles != null) {
Iterator fileit = formFiles.values().iterator();
while (fileit.hasNext()) {
FormFile forms = (FormFile) fileit.next();
System.out.println(forms.getFileName());//有输出证明上传成功 }
}

return null;
}
}
}

你可能感兴趣的:(Struts多附件上传)