jsp中的代码:
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html:html>
<head>
<title>上传文件</title>
</head>
<body>
<html:form action="/upload" method="post" enctype="multipart/form-data">
上传文件1:<html:file property="files[0]"></html:file><br/><br/><br/>
上传文件2:<html:file property="files[1]"></html:file><br/><br/><br/>
上传文件3:<html:file property="files[2]"></html:file><br/><br/><br/>
上传文件4:<html:file property="files[3]"></html:file><br/><br/><br/>
上传文件5:<html:file property="files[4]"></html:file><br/><br/><br/>
<html:submit>上传</html:submit>
</html:form>
</body>
</html:html>
ActionForm扩展代码:
package com.zhou.form;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm {
/**
*
*/
private static final long serialVersionUID = 4565221417769995006L;
private List<FormFile> list = new ArrayList<FormFile>() ;
public FormFile getFiles(int index){//struts中jsp中的form表单字段,在ActionForm中可以没有这个属性,但必须提供对应的get方法
return null ;
}
public void setFiles(int index,FormFile file){
//判断提供的上传连接用户有没有都是用,在list中只添加用户使用的files[]
if(file.getFileName()!=null&&!(file.getFileName()).equals("")){//
list.add(file) ;
}
}
public List<FormFile> getList(){
return this.list ;
}
}
Action代码:
package com.zhou.action;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import com.zhou.form.UploadForm;
public class UploadAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String path = this.getServlet().getServletContext().getRealPath("/upload") ;
UploadForm upf = (UploadForm)form ;
Iterator<FormFile> files = upf.getList().iterator() ;
if(!files.hasNext()){
return mapping.findForward("sucess") ;
}
int bytesRead = 0 ;
byte[] buffer = new byte[8192] ;
while(files.hasNext()){
FormFile file = files.next() ;
String fname = file.getFileName() ;
InputStream in = file.getInputStream() ;
OutputStream out = new FileOutputStream(path+"/"+fname);
while((bytesRead=in.read(buffer, 0, 8192))!=-1){
out.write(buffer,0,bytesRead) ;
}
out.close() ;
in.close() ;
file.destroy() ;
}
return mapping.findForward("sucess") ;
}
}