7、Struts2实现文件上传和下载

一、实现单个文件上传

1、创建如下web项目结构

2、在src下的com.action包下创建UploadAction.java

 1 package com.action;
 2 import java.io.File;
 3 
 4 import javax.servlet.ServletContext;
 5 
 6 import org.apache.commons.io.FileUtils;
 7 import org.apache.struts2.ServletActionContext;
 8 
 9 import com.opensymphony.xwork2.ActionSupport;
10 
11 /**
12  * 单个文件上传
13  * @author Dell
14  *
15  */
16 public class UploadAction extends ActionSupport {
17     //封装上传文件属性==form表单中file文件域的name属性值保持一致
18     private File upload;
19     
20     //封装上传文件的类型,固定语法=file文件域name属性值+ContextType;
21     private String uploadContentType;
22     
23     //封装文件上传名,固定语法=file文件域name属性值+FileName
24     private String uploadFileName;
25     
26     
27     @Override
28     public String execute() throws Exception {
29         //获取上下文对象
30         ServletContext appliaction=ServletActionContext.getServletContext();
31         //获取要保存文件的位置
32         String path=appliaction.getRealPath("/upload");
33         //创建一个与上传同名的文件
34         File file=new File(path,uploadFileName);
35         //将临时文件内容拷贝到目标文件夹下的那个同名的文件
36         FileUtils.copyFile(upload, file);
37         //删除临时文件
38         upload.delete();
39         return SUCCESS;
40     }
41     
42     public File getUpload() {
43         return upload;
44     }
45     public void setUpload(File upload) {
46         this.upload = upload;
47     }
48     public String getUploadContentType() {
49         return uploadContentType;
50     }
51     public void setUploadContentType(String uploadContentType) {
52         this.uploadContentType = uploadContentType;
53     }
54     public String getUploadFileName() {
55         return uploadFileName;
56     }
57     public void setUploadFileName(String uploadFileName) {
58         this.uploadFileName = uploadFileName;
59     }
60     
61 
62 }
UploadAction.java

3、在src下创建struts.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "struts-2.1.dtd" >
 3 <struts>
 4       <!-- 中文乱码处理 -->
 5       <constant name="struts.i18n.encoding" value="UTF-8"/>
 6       
 7       <constant name="struts.devMode" value="true"/>
 8        <!-- 设置上传文件的总大小 -->
 9       <constant name="struts.multipart.maxSize" value="200000000"/>
10       
11       <package name="default" namespace="/" extends="struts-default">
12       <!--文件上传 -->
13          <action name="*" class="com.action.{1}Action" method="execute">
14               <result>/success.jsp</result>
15               <result name="input">/error.jsp</result>
16               <interceptor-ref name="defaultStack">
17                  <!-- 配置文件上传的大小,这里配置的是上传文件的单个大小 -->
18                  <param name="fileUpload.maximumSize">20971520</param>
19                  
20                  <!-- 配置文件上传允许的类型 -->
21                  <param name="fileUpload.allowedTypes">text/plain,application/msword</param>
22                  
23                  <!-- 配置文件的扩展名 -->
24                  <param name="fileUpload.allowedExtensions">.txt,.doc</param>
25               </interceptor-ref>
26          </action>
27         
28       </package>
29 </struts>
struts.xml

4、在WebRoot下创建upload文件夹

5、编辑WebRoot下的WEB-INF下的web.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_9" 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">
 3     <filter>
 4         <filter-name>struts2</filter-name>
 5         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 6     </filter>
 7 
 8     <filter-mapping>
 9         <filter-name>struts2</filter-name>
10         <url-pattern>/*</url-pattern>
11     </filter-mapping>
12 
13     <welcome-file-list>
14         <welcome-file>upload.jsp</welcome-file>
15     </welcome-file-list>
16 
17 </web-app>
web.xml

6、在WebRoot下创建upload.jsp文件

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri=  "/struts-tags" prefix="s" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>单个文件上传</title>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   
24   <body> 
25     <s:form action="Upload.action" enctype="multipart/form-data" method="post">
26        <s:textfield name="title" label="标题"/><br/>
27        <s:file name="upload" label="选择文件"/><br/>
28        <s:submit name="submit" value="上传文件"/>
29     </s:form>
30   </body>
31 </html>
upload.jsp

7、在WebRoot下创建success.jsp文件

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="/struts-tags" prefix="s" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>My JSP 'index.jsp' starting page</title>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   
24   <body> 
25     上传成功!
26     您所上传的文件是:<s:property value="uploadFileName"/><br/>
27     文件类型:<s:property value="uploadContentType"/><br/>
28   </body>
29 </html>
success.jsp

8、在WebRoot下创建error.jsp文件

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'MyJsp.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26      操作失败!!
27   </body>
28 </html>
error.jsp

9、运行

二、上传多个文件

(接着上面的项目进行)

1、在src的com.action包下创建ManyUploadAction.java

 1 package com.action;
 2 import java.io.File;
 3 
 4 import javax.servlet.ServletContext;
 5 
 6 import org.apache.commons.io.FileUtils;
 7 import org.apache.struts2.ServletActionContext;
 8 
 9 import com.opensymphony.xwork2.ActionSupport;
10 
11 /**
12  * 多个文件上传
13  * @author Dell
14  *
15  */
16 public class ManyUploadAction extends ActionSupport {
17     //封装上传文件属性==form表单中file文件域的name属性值保持一致
18     private File[] upload;
19     
20     //封装上传文件的类型,固定语法=file文件域name属性值+ContextType;
21     private String[] uploadContentType;
22     
23     //封装文件上传名,固定语法=file文件域name属性值+FileName
24     private String[] uploadFileName;
25     
26     
27     @Override
28     public String execute() throws Exception {
29            //获取上下文对象
30             ServletContext appliaction=ServletActionContext.getServletContext();
31             //获取要保存文件的位置
32             String path=appliaction.getRealPath("/upload");
33             for (int i = 0; i < upload.length; i++) {
34                 
35             
36             //创建一个与上传同名的文件
37             File file=new File(path,uploadFileName[i]);
38             //将临时文件内容拷贝到目标文件夹下的那个同名的文件
39             FileUtils.copyFile(upload[i], file);
40             //删除临时文件
41             upload[i].delete();
42         }
43         return SUCCESS;
44     }
45 
46 
47     public File[] getUpload() {
48         return upload;
49     }
50 
51 
52     public void setUpload(File[] upload) {
53         this.upload = upload;
54     }
55 
56 
57     public String[] getUploadContentType() {
58         return uploadContentType;
59     }
60 
61 
62     public void setUploadContentType(String[] uploadContentType) {
63         this.uploadContentType = uploadContentType;
64     }
65 
66 
67     public String[] getUploadFileName() {
68         return uploadFileName;
69     }
70 
71 
72     public void setUploadFileName(String[] uploadFileName) {
73         this.uploadFileName = uploadFileName;
74     }
75     
76     
77 
78 
79 }
ManyUploadAction.java

2、在WebRoot下创建manyUpload.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri=  "/struts-tags" prefix="s" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>多个文件上传</title>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   
24   <body> 
25     <s:form action="ManyUpload.action" enctype="multipart/form-data" method="post">
26              <s:file name="upload" label="选择文件1"/><br/>
27              <s:file name="upload" label="选择文件2"/><br/>
28              <s:file name="upload" label="选择文件3"/><br/>
29              <s:file name="upload" label="选择文件4"/><br/>
30              <s:file name="upload" label="选择文件5"/><br/>
31         <s:submit name="submit" value="上传文件"/><br/>
32     </s:form>
33   </body>
34 </html>
manyUpload.jsp

3、运行

三、文件下载

 (接着上面的项目进行)

1、在src下的com.action包下创建FileDownAction.java

 1 package com.action;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.InputStream;
 7 
 8 import org.apache.struts2.ServletActionContext;
 9 
10 import com.opensymphony.xwork2.ActionSupport;
11 
12 /**
13  * 文件下载
14  * @author Dell
15  *
16  */
17 public class FileDownAction extends ActionSupport{
18     //读取下载文件的目录
19     private String inputPath;
20     //下载文件的文件名
21     private String fileName;
22     //读取下载文件的输入流
23     private InputStream inputStream;
24     //下载文件的类型
25     private String contentType;
26     
27     
28 
29     @Override
30     public String execute() throws Exception {
31         return SUCCESS;
32     }
33     
34     public String getInputPath() {
35         return inputPath;
36     }
37     public void setInputPath(String inputPath) {
38         this.inputPath = inputPath;
39     }
40     public String getFileName() {
41         return fileName;
42     }
43     public void setFileName(String fileName) {
44         this.fileName = fileName;
45     }
46     //创建InputStream输入流
47     public InputStream getInputStream() throws FileNotFoundException {
48         //得到下载文件的实际路径
49         String path=ServletActionContext.getServletContext().getRealPath(inputPath);
50         //创建输入流实现文件的下载读取
51         return new BufferedInputStream(new FileInputStream(path+"\\"+fileName));
52     }
53     public void setInputStream(InputStream inputStream) {
54         this.inputStream = inputStream;
55     }
56     public String getContentType() {
57         return contentType;
58     }
59     public void setContentType(String contentType) {
60         this.contentType = contentType;
61     }
62     
63 }
FileDownAction.java

2、编辑src下的struts.xml文件(添加文件下载的action的内容)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "struts-2.1.7.dtd" >
 3 <struts>
 4   <!-- 中文乱码处理 -->
 5   <constant name="struts.i18n.encoding" value="UTF-8"/>
 6   
 7   <!-- 设置开发模式 -->
 8   <constant name="struts.devMode" value="true"/>
 9   
10   <!-- 设置上传文件的大小 -->
11   <constant name="struts.multipart.maxSize" value="200000000"/>
12   
13   <package name="default" namespace="/" extends="struts-default">
14       <!-- 文件上传 -->
15       <action name="*" class="com.action.{1}Action" method="execute">
16          <result>/success.jsp</result>
17          <result name="input">/error.jsp</result>
18          <!-- 引用默认拦截器栈 -->
19          <interceptor-ref name="defaultStack">
20             <!-- 配置上传的大小,这里配置的是上传文件的单个大小 -->
21             <param name="fileUpload.maximumSize">20971520</param>
22             <!-- 配置文件上传允许的类型 -->
23             <!-- 图片:image/pjpeg,image/jpeg,image/gif,image/png,image/bmp -->
24             <!-- 文本文件:text/plain -->
25             <!-- HTML网页:text/html -->
26             <!-- 可执行文件:application/octet-stream -->
27             <!-- PPT:Application/vnd.ms-powerpoint -->
28             <!-- Excel:Application/vnd.ms-excel -->
29             <!-- Word:application/msword -->
30             <param name="fileUpload.allowedTypes">text/plain,application/msword</param>
31             <!-- 配置文件的扩展名 -->
32             <param name="fileUpload.allowedExtensions">.txt,.doc</param>
33         
34          </interceptor-ref>
35       </action>
36       
37       <!-- 文件下载 -->
38          <action name="download" class="com.action.FileDownAction" method="execute">
39              <!-- 配置action中使用的参数-->
40              <param name="inputPath">/upload</param>
41              
42              <result name="success" type="stream">
43                 <!--设置浏览器的文件类型  -->
44                 <param name="contentType">application/octet-stream</param>
45                 <!-- 输入流,读取 -->
46                 <param name="inputStream">inputStream</param>
47                 <!--设置http响应的头  -->
48                 <param name="contentDisposition">attachment;filename="${fileName}"</param>
49                 <!-- 设置缓冲区大小 -->
50                 <param name="bufferSize">4096</param>
51              </result>
52          </action>
53   </package>
54   </struts>
55   
56   
57   
58   
59   
60   
61   
struts.xml

3、在WebRoot下创建down.jsp页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri=  "/struts-tags" prefix="s" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>文件下载</title>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   
24   <body> 
25    <a href="download.action?fileName=20140914.txt">点击此处下载20140914.txt文档</a> 
26     
27   </body>
28 </html>
down.jsp

4、运行

posted @ 2016-05-24 21:50  红酒人生  阅读(607)  评论(1编辑  收藏  举报