今天看一本书上讲了关于struts2中如何实现文件上传,但是没有提到如何实现多文件上传,于是自己研究了一下,测试成功。 jsp页面代码: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <mce:script type="text/javascript"><!-- function addFile() { var td = document.getElementById("more"); var br = document.createElement("br"); var input = document.createElement("input"); var button = document.createElement("button"); input.type = "file"; input.name = "file"; button.value = "delete"; button.onclick = function(){ td.removeChild(br); td.removeChild(input); td.removeChild(button); } td.appendChild(br); td.appendChild(input); td.appendChild(button); } // --></mce:script> </head> <body> <form action="upload.action" method="post" enctype="multipart/form-data"> <table> <tr> <td id="more"> <input type="file" name="file" /><input type="button" value="more.." οnclick="addFile()"/> </td> </tr> <tr> <td> <input type="submit" value="upload" /> </td> </tr> </table> </form> </body> </html> 多文件上传的action代码如下: package cn.struts; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.opensymphony.xwork2.ActionSupport; public class FileUpload extends ActionSupport { /** * */ private static final long serialVersionUID = 1L; private File[] file; private String[] fileFileName; private String[] fileContentType; public String[] getFileFileName() { return fileFileName; } public void setFileFileName(String[] fileFileName) { this.fileFileName = fileFileName; } public String[] getFileContentType() { return fileContentType; } public void setFileContentType(String[] fileContentType) { this.fileContentType = fileContentType; } public File[] getFile() { return file; } public void setFile(File[] file) { this.file = file; } @Override public String execute() throws Exception { for(int i=0;i<file.length;i++) { byte[] buffer = new byte[1024]; InputStream is = new FileInputStream(file[i]); //"D:/"为服务器上的路径,可以自己设置 OutputStream os = new FileOutputStream("D:/"+fileFileName[i]); int length = is.read(buffer); while(length>0){ os.write(buffer); length = is.read(buffer); } is.close(); os.flush(); os.close(); } return SUCCESS; } } struts.xml配置文件: <package name="upload" namespace="/" extends="struts-default"> <action name="upload" class="cn.struts.FileUpload"> <result name="success">/uploadsuccess.jsp</result> </action> </package>