struts2.1 实现多文件上传及下载

多文件上传MultiFileUploadAction类ActionSupport

package com.struts2_uploadAndDownload.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
/**
 * 多文件上传
 * @author Camey
 *
 */
@SuppressWarnings("serial")
public class MultiFileUploadAction extends ActionSupport {
//	用户数组来接收上传文件
//	private File[] file;//使用Flie对象数组,接收多个上传文件
//	private String [] fileFileName;//使用数据保存多个上传文件的文件名
//	private String [] fileContentType;//使用数据保存多个上传文件的类型
//	private String uploadDir;//保存上传文件的目录,在struts.xml中配置
//	
//	public String execute(){
//		String newFileName=null;
//		//循环处理多个上传文件
//		for(int i=0; i<file.length; i++){
//			//得到当前时间开始流逝的毫秒数,将这个毫秒数做为新的文件名
//			long now=new Date().getTime();
//			int index=fileFileName[i].lastIndexOf(".");
//			
//			//得到保存上传文件的真实路径
//			String path=ServletActionContext.getServletContext().getRealPath(uploadDir);
//			File dir= new File(path);
//			//如果目录不存在就创建它
//			if (!dir.exists()) {
//				dir.mkdir();
//			}
//			//判断上传文件是否有扩展名
//			if (index!=-1) {
//				newFileName=now+fileFileName[i].substring(index);
//			}else {
//				newFileName=Long.toString(now);
//			}
//			
//			BufferedOutputStream bos=null;
//			BufferedInputStream bis=null;
//			//读取保存在临时目录下的上传文件,写入到新的文件中
//			try {
//				FileInputStream fis=new FileInputStream(file[i]);
//				bis=new BufferedInputStream(fis);
//				
//				FileOutputStream fos=new FileOutputStream(new File(dir,newFileName));
//				bos=new BufferedOutputStream(fos);
//				
//				byte [] buf=new byte[4096];
//				int len=-1;
//				while((len=bis.read(buf))!=-1){
//					bos.write(buf,0,len);
//				}
//			} catch (FileNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}finally{
//				if (bis!=null) {
//					try {
//						bis.close();
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//				if (bos!=null) {
//					try {
//						bos.close();
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//			}
//			
//		}
//		return SUCCESS;
//	}
//	
//	
//	public File[] getFile() {
//		return file;
//	}
//	public void setFile(File[] file) {
//		this.file = file;
//	}
//	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 String getUploadDir() {
//		return uploadDir;
//	}
//	public void setUploadDir(String uploadDir) {
//		this.uploadDir = uploadDir;
//	}
	
	
//	用户List来接收上传文件
	private List<File> file;
	private List<String> fileFileName;
	private List<String> fileContentType;
	private String uploadDir;
	
	public String execute(){
		
		String newFileName=null;
		//循环处理多个上传文件
		for(int i=0; i<file.size(); i++){
			//得到当前时间开始流逝的毫秒数,将这个毫秒数做为新的文件名
			long now=new Date().getTime();
			int index=fileFileName.get(i).lastIndexOf(".");
			
			//得到保存上传文件的真实路径
			String path=ServletActionContext.getServletContext().getRealPath(uploadDir);
			File dir= new File(path);
			//如果目录不存在就创建它
			if (!dir.exists()) {
				dir.mkdir();
			}
			//判断上传文件是否有扩展名
			if (index!=-1) {
				newFileName=now+fileFileName.get(i).substring(index);
			}else {
				newFileName=Long.toString(now);
			}
			
			BufferedOutputStream bos=null;
			BufferedInputStream bis=null;
			//读取保存在临时目录下的上传文件,写入到新的文件中
			try {
				FileInputStream fis=new FileInputStream(file.get(i));
				bis=new BufferedInputStream(fis);
				
				FileOutputStream fos=new FileOutputStream(new File(dir,newFileName));
				bos=new BufferedOutputStream(fos);
				
				byte [] buf=new byte[4096];
				int len=-1;
				while((len=bis.read(buf))!=-1){
					bos.write(buf,0,len);
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if (bis!=null) {
					try {
						bis.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (bos!=null) {
					try {
						bos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}
		
		return SUCCESS;
	}
	public List<File> getFile() {
		return file;
	}
	public void setFile(List<File> file) {
		this.file = file;
	}
	public List<String> getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}
	public List<String> getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}
	public String getUploadDir() {
		return uploadDir;
	}
	public void setUploadDir(String uploadDir) {
		this.uploadDir = uploadDir;
	}
}

文件下载Action

package com.struts2_uploadAndDownload.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
/**
 * 文件下载
 * @author Camey
 *
 */
public class FileDownloadAction implements Action {
	
	private String inputPath;//下载文件的路径在struts.xml文件中配置

	//inputStream属性的getter方法,StreamResult结果类型使用该属性来读取下载文件的内容
	public InputStream getInputStream(){
		return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
	}
	
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return SUCCESS;
	}
	
	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}
	public String getInputPath() {
		return inputPath;
	}

}

  自定义拦截器,实现动态的设置文件类型以及下载的文件名

package com.struts2_uploadAndDownload.interceptor;

import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;
/**
 * 自定义拦截器,实现动态的设置文件类型以及下载的文件名
 * @author Camey
 *
 */
@SuppressWarnings("serial")
public class FileDownloadInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		//调用ActionInvocation类的addPreResultListener方法注册PreResultListener实例
		invocation.addPreResultListener(new PreResultListener() {
			
			/*在beforeResult方法中,不能通过invocation.getResult()来得到Result对象,此时Result对象还没有
			创建,为null  为了修改传递给StreamResult的参数,可以通过如下方法调用来得到Result的配置信息,
			Result的配置信息封装在ResultConfig中*/
			public void beforeResult(ActionInvocation invocation, String resultCode) {
				// TODO Auto-generated method stub
				Map<String, ResultConfig> resultsMap=invocation.getProxy().getConfig().getResults();
				ResultConfig finalResultConfig=resultsMap.get(resultCode);
				
				//为了简单起见,这里通过硬编码下载文件的类型和下载文件名
				//在实际应用中,你可以读取数据库或配置文件来获取下载文件的信息
				//向ResultConfig对象添加参
				Map<String, String> configMap=new HashMap<String, String>(finalResultConfig.getParams());
				configMap.put("contentType", "image/jpeg");
				configMap.put("contentDisposition", "attachment;filename=\"1394544998139.psd\"");
			}
		});
		return invocation.invoke();
	}

}

 struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="default" namespace="/" extends="struts-default">
		<!-- 定义download拦截器 -->
		<interceptors>
			<interceptor name="FileDownloadInterceptor" class="com.struts2_uploadAndDownload.interceptor.FileDownloadInterceptor"/>
		</interceptors>
		<action name="MultiFileUploadAction" class="com.struts2_uploadAndDownload.action.MultiFileUploadAction">
			<result name="input">multiFileUpload.jsp</result>
			<result name="success">multiFileSuccess.jsp</result>
			<param name="uploadDir">uploadFiles</param>
		</action>
		
		<action name="FileDownloadAction" class="com.struts2_uploadAndDownload.action.FileDownloadAction">
			<interceptor-ref name="defaultStack"/>
			<interceptor-ref name="FileDownloadInterceptor"/>
		
			<!-- 指定下载文件的路径,该路径相对于web应用程序所在的目录 -->
			<param name="inputPath">uploadFiles/1394544998139.psd</param>
			
			<!-- 使用StreamResult结果类型 -->
			<result name="success" type="stream">
				<!-- inputName默认值是inputStream,如果action中用于读取下载文件内容的属性是
				inputStream,那么可以省略这个参数 -->
				<param name="inputName">inputStream</param>
				<param name="bufferSize">2048</param>
			</result>
		</action>
	</package>
</struts>    

 上传页面:multiFileUpload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'multiFileUpload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	<s:actionerror/>
  	<s:form action="MultiFileUploadAction" method="post" enctype="multipart/form-data">
  		<s:file name="file"></s:file>
  		<s:file name="file"></s:file>
  		<s:file name="file"></s:file>
  		<s:submit value="上传"></s:submit>
  	</s:form>  
  </body>
</html>

 上传成功页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'multiFileSuccess.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    上传成功. <br>
    文件名: <s:property value="fileFileName"/><br/>
    文件类型: <s:property value="fileContentType"/>
  </body>
</html>

 下载页面: download.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'download.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <s:url id="url" action="FileDownloadAction"></s:url>
    <s:a href="%{url}">下载</s:a>
  </body>
</html>

 

你可能感兴趣的:(struts2)