struts2文件上传1

文件上传概述

  要想使用 HTML 表单上传一个或多个文件, 必须把 HTML 表单的 enctype 属性设置为 multipart/form-data, 把它的 method 属性设置为 post
  为了让用户能够选择一个文件进行上传, 程序员必须提供一个 <input type=“file”> 字段

Struts 对文件上传的支持

  Struts 应用程序里, FileUpload 拦截器和 Jakarta Commons FileUpload 组件可以完成文件的上传.

  步骤:

    •1. 在 Jsp 页面的文件上传表单里使用 file 标签. 如果需要一次上传多个文件, 就必须使用多个 file 标签, 但它们的名字必须是相同的

    •2. 在 Action 中新添加 3 个和文件上传相关的属性. 这 3 个属性的名字必须是以下格式:

1 private File uploadImage; //上传的文件
2 private String uploadImageContentType;  //上传的文件的类型
3 private String uploadImageFileName;     //上传文件的名称   
•uploadImage 是 jsp 页面上的 file 标签的名字.

          上传文件:<input type="file" name="uploadImage">•如果是上传单个文件, uploadImage属性的类型就是 java.io.File, 它代表被上传的文件,

     第二个uploadImageContentType和第三个属性uploadImageFileName的类型是 String, 它们分别代表文件类型上传文件的文件名

 

          定义方式是分别是jsp页面file组件的名称+ContentType,jsp页面file组件的名称+FileName

•如果上上传多个文件, 可以使用数组或 List
 

单文件上传代码如下

  

定义上传出错要转向的页面

 1 第四步:在struts.xml文件中增加如下配置
 2  <package name="upload" namespace="/upload" extends="struts-default" >
 3           <!-- 单文件上传 -->
 4         <action name="uploadAction_*" class="cn.itcast.upload.UploadAction" method="{1}">
 5            <result name="success">/upload/success.jsp</result>
 6    
 7            <!-- 定义上传出错要转向的页面 -->
 8            <result name="input">/upload/error.jsp</result>
 9        </action>
10  <package>

设置上传文件的总开关

  

单文件上传总结:

 1 * 单文件上传:
 2         * 在动作类action中声明相关属性:
 3             * 在动作类action中,要声明与页面中表单name属性同名的属性,同名的属性的类型时File类型;
 4             * 在动作类action中,要声明[同名的属性]ContentType,类型时String类型;
 5             * 在动作类action中,要声明[同名的属性]FileName,类型时String类型
 6             * 给所有属性提供get和set方法
 7         * 在业务方法中,处理文件上传:
 8             * 获取要上传文件的路径,保存的位置
 9             * 在目标文件夹内,创建一个与上传文件同名的文件
10             * 通过FileUtils工具类提供copyFile()方法,将临时文件内容拷贝到目标文件夹下的那个同名的文件
11         * 设置上传文件的总大小
12             * 在struts.xml文件中,<constant name="struts.multipart.maxSize" value="2097152000"></constant>
13         * 设置上传文件的大小、类型和扩展名:
14             * 在自定义的配置文件中,在action标签下:
15                 <!-- 配置拦截器的参数,这里是文件上传拦截器 -->
16                 <interceptor-ref name="defaultStack">
17                       <!-- 
18                           配置文件上传拦截器的参数
19                               * 与定义参数的顺序无关
20                               * 允许的类型(allowedTypes)和允许的扩展名(allowedExtensions)必须保持一致
21                        -->
22                       <!-- 
23                           * 配置上传文件的大小
24                               * struts.xml文件中配置的是上传文件的总大小
25                               * 这里配置的是上传文件的单个大小
26                        -->
27                       <param name="fileUpload.maximumSize">20971520</param>
28                       <!-- 配置上传文件允许的类型,如果配置多个值的话,用","隔开 -->
29                       <param name="fileUpload.allowedTypes">text/plain,application/msword</param>
30                       <!-- 配置上传文件的扩展名,如果配置多个值的话,用","隔开 -->
31                       <param name="fileUpload.allowedExtensions">.txt</param>
32                 </interceptor-ref>
33              * 自定义上传文件的错误提示信息:
34                  * 在动作类action同目录下,创建一个名为fileuploadmessage.properties资源文件(名为自定义)
35                  * 改资源文件配置如下:
36                       struts.messages.error.uploading=Error uploading: {0}
37                     struts.messages.error.file.too.large=File too large: {0} "{1}" "{2}" {3}
38                     struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}
39                     struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}

样例代码:

1、jsp

  upload.jsp

 1 <%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib uri="/struts-tags"   prefix="s"%>
 3 <html>
 4   <head>
 5     <title>My JSP 'index.jsp' starting page</title>
 6     </head>
 7   <body>
 8     <form action="${pageContext.request.contextPath}/upload/uploadAction_saveFile.action"  
 9           name="form1"  method="post"  enctype="multipart/form-data" >
10              
11              上传文件名称:<input type="file" name="uploadImage">
12            <input type="submit" value="上传">
13     </form>
14   </body>
15 </html>

  success.jsp

 1 <%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib uri="/struts-tags"   prefix="s"%>
 3 <html>
 4   <head>
 5     <title>My JSP 'index.jsp' starting page</title>
 6     </head>
 7   <body>
 8         上传成功!!!!<br>
 9   </body>
10 </html>

  error.jsp

 1 <%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib uri="/struts-tags"   prefix="s"%>
 3 <html>
 4   <head>
 5     <title>My JSP 'index.jsp' starting page</title>
 6     </head>
 7   <body>
 8                 失败!!!!<br>
 9               <s:fielderror/>
10      </body>
11 </html>

2、java

  UploadAction.java

 1 import java.io.File;
 2 import java.io.IOException;
 3 
 4 import javax.servlet.ServletContext;
 5 import javax.servlet.http.HttpServletRequest;
 6 
 7 import org.apache.commons.io.FileUtils;
 8 import org.apache.struts2.ServletActionContext;
 9 
10 import com.opensymphony.xwork2.ActionSupport;
11 
12 @SuppressWarnings("serial")
13 public class UploadAction extends ActionSupport {
14     
15     /*
16      * 上传文件的存储的临时文件:
17      * E:\\TOOLS\\apache-tomcat-6.0.35\\work\\Catalina\\localhost\\itcast1105_struts\\upload__5fee1dc7_13ad3d1835b__8000_00000000.tmp
18      */
19     private File uploadImage;
20     
21     //上传文件的类型:text/plain
22     private String uploadImageContentType;//application/zip
23     
24     //上传文件的真是名称 2013年上期大学生信用档案建设.zip
25     private String uploadImageFileName;
26     
27     public File getUploadImage() {
28         return uploadImage;
29     }
30 
31     public void setUploadImage(File uploadImage) {
32         this.uploadImage = uploadImage;
33     }
34 
35     public String getUploadImageContentType() {
36         return uploadImageContentType;
37     }
38 
39     public void setUploadImageContentType(String uploadImageContentType) {
40         this.uploadImageContentType = uploadImageContentType;
41     }
42 
43     public String getUploadImageFileName() {
44         return uploadImageFileName;
45     }
46 
47     public void setUploadImageFileName(String uploadImageFileName) {
48         this.uploadImageFileName = uploadImageFileName;
49     }
50 
51     public String saveFile(){
52         System.out.println("UploadAction *********** saveFile()");
53         
54         ServletContext sc = ServletActionContext.getServletContext();
55         
56         String path = sc.getRealPath("/fileupload");//request下的该方法过时了
57         
58         File file = new File(path, uploadImageFileName);
59         
60         try {
61             
62             FileUtils.copyFile(uploadImage, file);
63             
64         } catch (IOException e) {
65             e.printStackTrace();
66         }
67         
68         uploadImage.delete();//高版本支持自动清空,低版本不支持
69         
70         return "success";
71     }
72     
73 }

3、xml

  struts_upload.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 <struts>
 6     <!--        /upload/uploadAction_saveFile.action        -->
 7     <package name="upload" namespace="/upload"  extends="struts-default"> 
 8          <action name="uploadAction_saveFile" class="cn.zengfansheng.struts.upload.UploadAction"  method="upload">
 9             <result name="success">
10                 <param name="location">/upload/success.jsp</param>
11             </result>
12             <result name="input">/upload/error.jsp</result>
13          </action>
14     </package>
15 </struts>

  struts.xml

1 <!-- 配置文件上传的总大小 -->
2     <constant name="struts.multipart.maxSize" value="2097152000"></constant>
3   <include file="cn/zengfansheng/struts/upload/struts_upload.xml"></include>

  <constant name="struts.custom.i18n.resources" value="cn.zengfansheng.struts.upload.fileuploadmessage"></constant>
  <!-- 省略后缀名,如果配置了多个struts.custom.i18n.resources,后面的会覆盖前面的,出现不起效果 -->

 4、properties

  fileuploadmessage.properties

1 struts.messages.error.uploading=\u4E0A\u4F20\u51FA\u9519\: {0}
2 struts.messages.error.file.too.large=\u6587\u4EF6\u8FC7\u5927\: {0} "{1}" "{2}" {3}
3 struts.messages.error.content.type.not.allowed=\u7C7B\u578B\u4E0D\u5141\u8BB8\: {0} "{1}" "{2}" {3}
4 struts.messages.error.file.extension.not.allowed=\u6269\u5C55\u540D\u4E0D\u5141\u8BB8\: {0} "{1}" "{2}" {3}
原文地址:https://www.cnblogs.com/hacket/p/3082206.html