Posted on 2007-04-27 14:52
semovy 阅读(424)
评论(0) 编辑 收藏 所属分类:
struts
主要代码如下
Form部分:
public class MultiUploadForm extends ActionForm {
private List myFiles;
public MultiUploadForm(){
myFiles = new ArrayList();
//为了能够在页面初始显示一个file
myFiles.add(new UploadFile());
}
public List getMyFiles() {
return myFiles;
}
//注意这个方法的定义
public UploadFile getUploadFile(int index){
int size = myFiles.size();
if(index>size-1){
myFiles.add(new UploadFile());
}
return (UploadFile)myFiles.get(index);
}
public void setMyFiles(List myFiles) {
this.myFiles = myFiles;
}
}
Dataset部分:
public class UploadFile implements Serializable {
private FormFile file;
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) {
MultiUploadForm multiUploadForm = (MultiUploadForm) form;
List myFiles = multiUploadForm.getMyFiles();
for(int i =0;i<myFiles.size();i++){
UploadFile uploadFile = (UploadFile)myFiles.get(i);
FormFile file = uploadFile.getFile();
if(file==null){
System.out.println("file is null");
}
else{
//能运行到这里,就可以使用单个文件上传的方法进行上传了。循环而已
System.out.println("filename:::" + file.getFileName());
System.out.println("file size:::" + file.getFileSize());
}
}
return null;
}
}
JSP部分:
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-nested.tld" prefix="nested" %>
<html:html>
<head>
<title>
multiUploadDemo
</title>
</head>
<script language="javascript" type="">
var num = 0;
function upload(){
multiUploadForm.submit();
}
function additem(id)
{
var row,cell,str;
row = eval("document.all["+'"'+id+'"'+"]").insertRow();
if(row != null )
{
cell = row.insertCell();
str="<input type="+'"'+"file"+'"'+" name=uploadFile["+ num +"].file><input type="+'"'+"button"+'"'+" value="+'"'+"删除"+'"'+" onclick='deleteitem(this,"+'"'+"tb"+'"'+");'>"
cell.innerHTML=str;
}
num++;
}
function deleteitem(obj,id)
{
var rowNum,curRow;
curRow = obj.parentNode.parentNode;
rowNum = eval("document.all."+id).rows.length - 1;
eval("document.all["+'"'+id+'"'+"]").deleteRow(curRow.rowIndex);
}
</script>
<body bgcolor="#ffffff">
<html:form method="post" action="/multiUploadAction.do" enctype="multipart/form-data">
<table id="tb">
</table>
</html:form>
<input type="button" name="btnAddFile" value="Add File" onclick="additem('tb')"/>
<input type="button" name="btnUpload" value="upload" onclick="upload()"/>
</body>
</html:html>
struts-config.xml部分:
<form-beans>
<form-bean name="multiUploadForm" type="MultiUploadForm" />
</form-beans>
<action name="multiUploadForm" path="/multiUploadAction" type="MultiUploadAction" />
以上只是对动态多文件上传部分进行了描述,只是一个Demo。大家可以根据自己的需求变通的调整一下。