之前写过一篇文章,关于Struts2文件上传:http://www.cnblogs.com/lichenwei/p/3927964.html
现在来说下多文件上传,其实就把上传文件当成是一个数组去处理,和单文件上传是一样的思路,直接贴一段代码:
uploads.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!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=ISO-8859-1"> <title>上传文件示例</title> </head> <body> <s:actionerror/> <s:fielderror/> <s:form action="uploads.action" theme="simple" namespace="/" method="post" enctype="multipart/form-data"> <s:file label="上传文件:" name="upload"></s:file> <s:file label="上传文件:" name="upload"></s:file> <s:file label="上传文件:" name="upload"></s:file> <s:submit value="提交上传"></s:submit> </s:form> </body> </html>
UploadsAction.java
package com.lcw.struts2.upload; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadsAction extends ActionSupport { // <s:file label="上传文件:" name="upload"></s:file> private File[] upload;// 命名应该和上传页面name属性值保持一致 private String[] uploadContentType;// 属性值+ContentType private String[] uploadFileName;// 属性值+FielName public void setUpload(File[] upload) { this.upload = upload; } public void setUploadContentType(String[] uploadContentType) { this.uploadContentType = uploadContentType; } public void setUploadFileName(String[] uploadFileName) { this.uploadFileName = uploadFileName; } public String upload() { for (int i = 0; i < upload.length; i++) { File destFile = new File(ServletActionContext.getServletContext() .getRealPath("/uploads") + "/" + uploadFileName[i]); try { // 工具类 FileUtils.copyFile(upload[i], destFile); } catch (IOException e) { e.printStackTrace(); } } return SUCCESS; } }
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.multipart.maxSize" value="20000000000"></constant> <!-- 全局国际化配置 --> <constant name="struts.custom.i18n.resources" value="messages"></constant> <package name="struts2test" extends="struts-default"> <action name="uploads" class="com.lcw.struts2.upload.UploadsAction" method="upload"> <result name="success">/index.jsp</result> <result name="input">/upload.jsp</result> </action> </package> </struts>
来看下效果图: