- 其他struts2 文件上传与下载原理 详细资料:http://blog.csdn.net/lisa0220/article/details/6400767
- /**
- * Struts2Test
- * 使用Struts2上传文件
- */
- package com.labci.struts2.action;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import com.opensymphony.xwork2.ActionSupport;
- public class UploadFileAction extends ActionSupport implements
- ServletRequestAware {
- private static final long serialVersionUID = -1896915260152387341L;
- private HttpServletRequest request;
- public void setServletRequest(HttpServletRequest req) {
- this.request=req;
- }
- private List<File> fileName;//这里的"fileName"一定要与页面表单中的文件域名相同(获取上传文件)
- private List<String> fileNameContentType;//格式同上"fileName"+ContentType(固定格式)
- private List<String> fileNameFileName;//格式同上"fileName"+FileName(固定格式)
- private String savePath;//文件上传后保存的路径(在struts.xml中配置,也可在后台定义)
- private String allowTypes;//允许上传的文件类型(在struts.xml中配置,也可在后台定义)
- public List<File> getFileName() {
- return fileName;
- }
- public void setFileName(List<File> fileName) {
- this.fileName = fileName;
- }
- public List<String> getFileNameContentType() {
- return fileNameContentType;
- }
- public void setFileNameContentType(List<String> fileNameContentType) {
- this.fileNameContentType = fileNameContentType;
- }
- public List<String> getFileNameFileName() {
- return fileNameFileName;
- }
- public void setFileNameFileName(List<String> fileNameFileName) {
- this.fileNameFileName = fileNameFileName;
- }
- @SuppressWarnings("deprecation")
- public String getSavePath() {
- return request.getRealPath(savePath);
- }
- public void setSavePath(String savePath) {
- this.savePath = savePath;
- }
- public String getAllowTypes() {
- return allowTypes;
- }
- public void setAllowTypes(String allowTypes) {
- this.allowTypes = allowTypes;
- }
- @Override
- public String execute() throws Exception {
- //验证上传的文件
- List<String> fileTypes=getFileNameContentType(); ---获得上传文件的类型
- String []allowTypes=getAllowTypes().split(","); ---获得配置的允许上传文件类型
- List<String> typesList=Arrays.asList(allowTypes);
- boolean allowFlag=true; --是否存在不允许上传的文件类型
- for(String type:fileTypes){
- if(!typesList.contains(type)){
- allowFlag=false;
- break;
- }
- }
- if(!allowFlag){
- request.setAttribute("fileTypeError",
- "您上传的文件中存在不允许上传的类型,允许上传的类型为:"+getAllowTypes());
- return INPUT;
- }
- //指定文件保存的路径
- File dir=new File(getSavePath());
- if(!dir.exists()){
- dir.mkdirs();
- }
- List<File> files=getFileName(); ---获取所有上传的文件
- for(int i=0;i<files.size();i++){
- //构造服务器内存写入磁盘的输出流
- FileOutputStream fos=new FileOutputStream(getSavePath()+"//"+getFileNameFileName().get(i));
- //构造服务器内存读取上传文件的输入流
- FileInputStream fis=new FileInputStream(getFileName().get(i));
- byte []buffers=new byte[1024];
- int len=0;
- while((len=fis.read(buffers))!=-1){ //读取文件
- fos.write(buffers,0,len); //写入文件
- }
- }
- //构造返回页面的数据
- List<String> fileHrefsList=new ArrayList<String>();
- for(String fileName:getFileNameFileName()){ ---遍历所有上传文件的名称
- String href="<a href="/" mce_href="/""downloadFile.action?fileName="+fileName+"/">"+fileName+"</a>";
- fileHrefsList.add(href);
- }
- request.setAttribute("fileNameList", fileHrefsList);
- return SUCCESS;
- }
- }
----------------------------------------index.jsp---------------------------------------------------------------------------
- <%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2多文件上传</title>
- </head>
- <body>
- <table>
- <tr>
- <td>
- <c:choose>
- <c:when test="${!empty fileTypeError}">
- <font color="red"><b>${fileTypeError}</b></font>
- </c:when>
- <c:otherwise>
- <c:forEach items="${fileNameList}" var="fileName">
- ${fileName}<br/>
- </c:forEach>
- </c:otherwise>
- </c:choose>
- </td>
- </tr>
- </table>
- <!-- 不一定要选择所有文件才可以上传 -->
- <form action="uploadFile.action" method="post" enctype="multipart/form-data">
- <input type="file" name="fileName"/><br/>
- <input type="file" name="fileName"/><br/>
- <input type="file" name="fileName"/><br/>
- <input type="submit" value="上传"/>
- </form>
- </body>
- </html>
---------------------------------------web.xml--------------------------------------------------------------------------------
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.FilterDispatcher
- </filter-class>
- </filter>
- <filter-mapping>
- <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>
-------------------------------------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="false" />
- <!-- 改变struts2默认为2M的上传文件大小限制 -->
- <constant name="struts.multipart.maxSize" value="10240000"/>
- <package name="upload" extends="struts-default">
- <action name="uploadFile" class="com.labci.struts2.action.UploadFileAction">
- <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>
- <result name="success">index.jsp</result>
- <result name="input">index.jsp</result>
- </action>
- <action name="downloadFile" class="com.labci.struts2.action.DownloadFileAction">
- <param name="savePath">/upload</param>
- <result name="success">index.jsp</result>
- </action>
- </package>
- </struts>
=============================下载========================================================
- /**
- * Struts2Test
- * 文件下载的Action
- */
- package com.labci.struts2.action;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import org.apache.struts2.interceptor.ServletResponseAware;
- import com.opensymphony.xwork2.ActionSupport;
- public class DownloadFileAction extends ActionSupport implements
- ServletRequestAware, ServletResponseAware {
- private static final long serialVersionUID = -7448748577778248376L;
- private HttpServletRequest request;
- private HttpServletResponse response;
- private String savePath; //文件上传后保存的路径(在struts.xml中配置,也可在后台定义)
- @Override
- public String execute() throws Exception {
- String fileName=request.getParameter("fileName");---页面请求参数文件名(上传返回页面时指定的)
- String fullPath=getSavePath()+"//"+fileName; //构造文件源的完整路径
- fileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");
- InputStream is=new FileInputStream(fullPath); //构造服务器内存读取源文件的输入流
- int len=0;
- byte []buffers=new byte[1024];
- response.reset();
- response.setContentType("application/x-msdownload"); ---设置文件返回页面的类型
- response.addHeader("Content-Disposition", "attachment;filename=/""+fileName+"/"");---返回的名称
- //把文件内容通过输出流打印到页面上供下载
- while((len=is.read(buffers))!=-1){ //内存读取
- OutputStream os=response.getOutputStream(); //获得输出文件的流
- os.write(buffers, 0, len); //输出
- }
- is.close();
- return SUCCESS;
- }
- public void setServletRequest(HttpServletRequest req) {
- this.request=req;
- }
- public void setServletResponse(HttpServletResponse resp) {
- this.response=resp;
- }
- @SuppressWarnings("deprecation")
- public String getSavePath() {
- return request.getRealPath(savePath);
- }
- public void setSavePath(String savePath) {
- this.savePath = savePath;
- }
- }
---------------------------------------------------------------------------------------------------------