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、在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

3、运行

时间: 2024-11-05 13:46:18

7、Struts2实现文件上传和下载的相关文章

struts2实现文件上传和下载

在做B/S系统时,通常会涉及到上传文件和下载文件,在没接struts2框架之前,我们都是使用apache下面的commons子项目的FileUpload组件来进行文件的上传,但是那样做的话,代码看起来比较繁琐,而且不灵活,在学习了struts2后,struts2为文件上传下载提供了更好的实现机制,在这里我分别就单文件上传和多文件上传的源代码进行一下讲解,这里需要导入文件下载上传的两个jar文件,一个是commons-fileupload-1.2.2.jar,另一个是commons-io-2.0.

Struts2入门(七)——Struts2的文件上传和下载

一.前言 在之前的随笔之中,我们已经了解Java通过上传组件来实现上传和下载,这次我们来了解Struts2的上传和下载. 注意:文件上传时,我们需要将表单提交方式设置为"POST"方式,并且将enctype属性设置为"multipart/form-data",该属性的默认值为"application/x-www-form-urlencoded",就是说,表单要写成以下这种形式: <form action="" metho

struts2(六) 文件上传和下载

前面对文件下载提过一点点,这里正好要讲文件上传,就放在一起在说一遍. --WH 一.单文件上传 在没学struts2之前,我们要写文件上传,非常麻烦,需要手动一步步去获取表单中的各种属性,然后在进行相应的处理,而在struts2中就不需要了,因为有一个fileUpload拦截器帮我们全做完了.我们只需要添加一点点信息,就可以完成上传的功能. 1.Action中需要提供三个属性 File fieldName: //文件表单项名称,也就是上传控件所填写的name属性名 String fileCont

Struts2 实现文件上传和下载

实现上传功能 1.首先你应该有一个上传页面 <!-- file的name属性与action中的File类型属性保持一致,用于封装File控件对应的文件内容 --> <s:file name="upload" label="选择文件"></s:file> 2.然后创建一个文件上传的XXXaction public class UploadAction extends ActionSupport implements ModelDri

struts2中的文件上传和下载

天下大事,必做于细.天下难事,必作于易. 曾经见过某些人,基础的知识还不扎实就去学习更难的事,这样必然在学习新的知识会很迷惑结果 再回来重新学习一下没有搞懂的知识,这必然会导致学习效率的下降!我写的这篇上传和下载都很基础. 十分适合初学者! jsp:页面 <!--在进行文件上传时,表单提交方式一定要是post的方式,因为文件上传时二进制文件可能会很大,还有就是enctype属性,这个属性一定要写成multipart/form-data, 不然就会以二进制文本上传到服务器端--> <for

Struts2文件上传与下载

一,页面 index.html 在页面中最重要的就是这个文件上传用的 form 表单,注意这里一定要把 form 的encyType属性明确标定为“multipart/form-data”,只有这样.表单才可能以二进制的形式上传到服务器. <form action = "<%=contextPath%>/file/uploadImage.action" encytype="multipart/form-data"> <input typ

Struts2学习总结——文件上传与下载

Struts2文件上传与下载 1.1.1新建一个Maven项目(demo02) 在此添加Web构面以及 struts2 构面 1.2.1配置Maven依赖(pom.xml 文件) <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20

Struts2学习(八)—文件上传和下载

在做B/S系统时,通常会涉及到上传文件和下载文件,在没接struts2框架之前,我们都是使用apache下面的commons子项目的FileUpload组件来进行文件的上传,但是那样做的话,代码看起来比较繁琐,而且不灵活,在学习了struts2后,struts2为文件上传下载提供了更好的实现机制,在这里我分别就单文件上传和多文件上传的实现进行一下讲解,这里 我们使用的struts2 web项目所导入的jar包中的**commons-fileupload-1.3.1.jar commons-io-

struts2 实现文件上传下载 (下载支持中文文件名)代码

struts2 实现文件上传: Action 代码: package com.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.apache.struts2.ServletActionContext; import com.o