首先创建一个简单的project,配置其中的web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>applicationProject</display-name>
<filter>
<!-- 配置Struts2核心Filter的名字 -->
<filter-name>struts2</filter-name>
<!-- 配置Struts2核心Filter的实现类 -->
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- 配置Filter拦截的URL -->
<filter-mapping>
<!-- 配置Struts2的核心FilterDispatcher拦截所有用户请求 -->
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp页面信息:
<!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"> <%@ page language="java" contentType="text/html;" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <title>文件上传</title> </head> <script type="text/javascript"> function checkf() { var files = document.getElementsByName("file"); if (files[0].value.length != 0) { return true; } else { alert("请选择文件"); return false; } } function addMore() { var td = document.getElementById("more"); var br = document.createElement("br"); var input = document.createElement("input"); var button = document.createElement("input"); input.type = "file"; input.name = "file"; button.type = "button"; button.value = "Remove"; button.onclick = function() { td.removeChild(br); td.removeChild(input); td.removeChild(button); } td.appendChild(br); td.appendChild(input); td.appendChild(button); } </script> <body> <form action="upload.action" method="post" enctype="multipart/form-data"> <table align="center" width="50%" border="1"> <tr> <td>选择上传文件</td> <td id="more"> <input type="file" id="file" name="file"> <input type="button" value="Add More.." onclick="addMore();"> </td> </tr> <tr> <td><input type="submit" value="submit" onclick="return checkf();" /></td> </tr> </table> <div>${fileTypeError}</div> </form> </body> </html> success.jsp页面信息: <pre name="code" class="html"><%@ page language="java" contentType="text/html;" pageEncoding="utf-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <!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>文件下载</title> </head> <body> <s:form> <div style="border:1px solid black">成功上传的文件:<br> <ul style="list-style-type:decimal"> <c:forEach items="${fileNames}" var="viewFile" varStatus="ind" > 下载文件${ind.index+1}: <a href="download.action?filename=${viewFile}">${viewFile}</a></br> </c:forEach> </ul> </div> </s:form> </body> </html>
<?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.i18n.encoding" value="utf-8"></constant> <constant name="struts.multipart.saveDir" value="/upload"></constant> <package name="struts2" namespace="/" extends="struts-default"> <action name="upload" class="com.huaxun.system.UpDownloadAction" method="upLoadFile"> <result name="input">/index.jsp</result> <result name="success">/success.jsp</result> <param name="maximumSize">409600</param> <param name="savePath">/upload</param> <param name="allowTypes">text/plain,text/xml,text/html,image/gif,image/png,image/jpeg,image/jpg,image/bmp</param> <interceptor-ref name="defaultStack"></interceptor-ref> </action> <action name="download" class="com.huaxun.system.UpDownloadAction" method="downLoadFile"> <param name="savePath">/upload</param> <result name="success">success.jsp</result> <result name="input">/index.jsp</result> <interceptor-ref name="defaultStack"></interceptor-ref> </action> </package> </struts>
package com.huaxun.system; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UpDownloadAction extends ActionSupport { private static final long serialVersionUID = 1L; private List<File> file;//这里的文件域名 一定要和表单中的file名相同 private List<String> fileFileName;//格式和“file”+FileName private List<String> fileContentType;//上传文件 内容类型 file +"ContentType" private String savePath;//上传文件保存的路径 private String allowTypes;//允许上传文件的类型 private HttpServletRequest request = ServletActionContext.getRequest(); public String upLoadFile() throws Exception { List<String> typeList = getFileContentType(); String[] allowTs = getAllowTypes().split(","); List<String> list =Arrays.asList(allowTs); boolean result = true;//先判断上传的文件 是否为允许上传的文件类型 for (String type : typeList) { if(!list.contains(type)){ result = false; break; } } //不允许 if(!result){ request.setAttribute("fileTypeError", "允许上传的文件类型为:"+ getAllowTypes()); return INPUT; } //允许上传 InputStream is = null;//读取文件 OutputStream os = null;//写入文件 File desFile = new File(getSavePath()); if(desFile.mkdir()){ desFile.mkdir(); } for (int i = 0; i < file.size(); i++) { is = new FileInputStream(file.get(i)); os = new FileOutputStream(getSavePath()+"//"+this.getFileFileName().get(i)); byte[] buffer = new byte[1024]; int length = 0; try{ while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } }finally{ if(null != is){ is.close(); } if(null != os){ os.close(); } } } request.setAttribute("fileNames", fileFileName); return SUCCESS; } public String downLoadFile() throws IOException{ String fileNameStr = request.getParameter("filename"); String fullName= getSavePath()+"\\"+fileNameStr; InputStream inputStream = new FileInputStream(fullName); HttpServletResponse response = ServletActionContext.getResponse(); OutputStream out = response.getOutputStream(); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment;fileName=\"" + new String( fileNameStr.getBytes("gb2312"), "ISO8859-1" ) +"\""); int leng = 0; byte[] buffer = new byte[1024]; while((leng = inputStream.read(buffer, 0, buffer.length)) != -1){ out.write(buffer, 0, leng); } if(null != out){ out.close(); } if(null != inputStream){ inputStream.close(); } return null; } /** * @return the file */ public List<File> getFile() { return file; } /** * @param file the file to set */ public void setFile(List<File> file) { this.file = file; } /** * @return the fileFileName */ public List<String> getFileFileName() { return fileFileName; } /** * @param fileFileName the fileFileName to set */ public void setFileFileName(List<String> fileFileName) { this.fileFileName = fileFileName; } /** * @return the fileNameContentType */ public List<String> getFileContentType() { return fileContentType; } /** * @param fileNameContentType the fileNameContentType to set */ public void setFileContentType(List<String> fileContentType) { this.fileContentType = fileContentType; } /** * @return the savePath */ public String getSavePath() {//获取绝对路径 return ServletActionContext.getServletContext().getRealPath(savePath); } /** * @param savePath the savePath to set */ public void setSavePath(String savePath) { this.savePath = savePath; } /** * @return the allowType */ public String getAllowTypes() { return allowTypes; } /** * @param allowType the allowType to set */ public void setAllowTypes(String allowTypes) { this.allowTypes = allowTypes; } }
效果图: