• [原创]java WEB学习笔记72:Struts2 学习之路-- 文件的上传下载,及上传下载相关问题


    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

    内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

    本人互联网技术爱好者,互联网技术发烧友

    微博:伊直都在0221

    QQ:951226918

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    1.文件上传

      1)表单需要注意三点:

         ① 须把 HTML 表单的 enctype 属性设置为 multipart/form-data

           ②须把 HTML 表单的method 属性设置为 post

         ③需添加 <input type=“file”> 字段. 

      2)Struts2 的文件上传实际使用的是Common FileUpload 组件,导入jar包。commons-fileupload / commons-io 

      3)Struts2 进行文件上传需要使用FileUpload拦截器

      4)基本的文件操作:直接在Action 中定义如下 3个属性,并提供对应的get / set方法

           private File  [fileFieldName];    //文件对应的file 对象

         private String  [fileFieldName]ContentType; // 文件类型

         private String  [fileFieldName]pptFileName; // 文件名

      5)使用IO 流进行文件的上传

     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 
     6 <struts>
     7  
     8  
     9      <!-- 配置国际化资源文件 -->
    10      <constant name="strut2.custom.i18n.resouce" value="i18n"></constant>
    11      
    12      <constant name="struts.action.extension" value="action,do,"></constant>
    13      <package name="default" namespace="/" extends="struts-default">
    14      
    15          <action name="testUpload" class="com.jason.upload.app.UploadAction">
    16              <result>/sucess.jsp</result>
    17          </action>
    18          
    19      </package>
    20     
    21 </struts>
    struts.xml
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%@ taglib prefix="s" uri="/struts-tags" %>
     4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     5 <html>
     6 <head>
     7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     8 <title>Insert title here</title>
     9 </head>
    10 <body>
    11 
    12     <s:form action="testUpload" method="post" enctype="multipart/form-data">
    13         <s:file name="ppt" label="PPTfile"></s:file>
    14         <s:textfield  name="pptDesc" label="PPTDesc"></s:textfield>
    15         
    16         <s:submit></s:submit>
    17     </s:form>
    18     
    19 
    20 </body>
    21 </html>
    upload.jsp
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 
    11     <h4> success page</h4>
    12 </body>
    13 </html>
    sucess.jsp
     1 package com.jason.upload.app;
     2 
     3 import java.io.File;
     4 import java.io.FileInputStream;
     5 import java.io.FileOutputStream;
     6 
     7 import javax.servlet.Servlet;
     8 import javax.servlet.ServletContext;
     9 
    10 import org.apache.struts2.ServletActionContext;
    11 
    12 import com.opensymphony.xwork2.ActionSupport;
    13 
    14 public class UploadAction extends ActionSupport {
    15 
    16     /**
    17      * @Fields:serialVersionUID
    18      */
    19     private static final long serialVersionUID = 1L;
    20 
    21     private File ppt;
    22     private String pptContentType;
    23     private String pptFileName;
    24     
    25     
    26     public File getPpt() {
    27         return ppt;
    28     }
    29 
    30     public void setPpt(File ppt) {
    31         this.ppt = ppt;
    32     }
    33 
    34     public String getPptContentType() {
    35         return pptContentType;
    36     }
    37 
    38     public void setPptContentType(String pptContentType) {
    39         this.pptContentType = pptContentType;
    40     }
    41 
    42     public String getPptFileName() {
    43         return pptFileName;
    44     }
    45 
    46     public void setPptFileName(String pptFileName) {
    47         this.pptFileName = pptFileName;
    48     }
    49     
    50     
    51     @Override
    52     public String execute() throws Exception {
    53     
    54         ServletContext  servletContext = ServletActionContext.getServletContext();
    55         
    56         String dir = servletContext.getRealPath("/files/" + pptFileName);
    57         System.out.println(dir);
    58         
    59         FileOutputStream out = new FileOutputStream(dir);
    60         FileInputStream in = new FileInputStream(ppt);
    61         
    62         byte[] buffer = new byte[1024];
    63         int len = 0;
    64         while((len = in.read(buffer)) != -1){
    65             out.write(buffer, 0, len);
    66         }
    67           out.close();
    68           in.close();
    69         
    70         
    71         System.out.println(ppt);
    72         System.out.println(pptContentType);
    73         System.out.println(pptFileName);
    74         return SUCCESS;
    75     }
    76 
    77 }
    UploadAction.java

    2.相关问题

      1)一次性上传过个文件?

       若传递多个文件,则上述3个属性,可以改为list类型,多个文件的name 属性需要一致

        

     1 <s:form action="testUpload" method="post" enctype="multipart/form-data">
     2         <s:file name="ppt" label="PPTfile"></s:file>
     3         <s:textfield  name="pptDesc[0]" label="PPTDesc"></s:textfield>
     4         
     5         <s:file name="ppt" label="PPTfile"></s:file>
     6         <s:textfield  name="pptDesc[1]" label="PPTDesc"></s:textfield>
     7         
     8         <s:file name="ppt" label="PPTfile"></s:file>
     9         <s:textfield  name="pptDesc[2]" label="PPTDesc"></s:textfield>
    10         
    11         <s:file name="ppt" label="PPTfile"></s:file>
    12         <s:textfield  name="pptDesc[3]" label="PPTDesc"></s:textfield>
    13         
    14         <s:submit></s:submit>
    15     </s:form>

      

      

    1     private List<File> ppts;
    2     private String pptContentType;
    3     private String pptFileName;

      2)对上传文件的限制?例如扩展名,内容类型,上传文件的大小?如果出错, 显示错误消息?消息可以定制?

    Interceptor parameters: 
    
    •maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be set on the action. Note, this is not related to the various properties found in struts.properties. Default to approximately 2MB.
    
    默认文件的最大值2M,上传的单个文件
    
    •allowedTypes (optional) - a comma separated list of content types (ie: text/html) that the interceptor will allow a file reference to be set on the action. If none is specified allow all types to be uploaded.
    允许上传的文件类型,多个使用 ',' 分割
    
    •allowedExtensions (optional) - a comma separated list of file extensions (ie: .html) that the interceptor will allow a file reference to be set on the action. If none is specified allow all extensions to be uploaded.
    允许的上传文件的类型,多个使用 ‘ , ’分割

     

    定制文件上传错误消息

    This interceptor will add several field errors, assuming that the action implements ValidationAware. These error messages are based on several i18n values stored in struts-messages.properties, a default i18n file processed for all i18n requests. You can override the text of these messages by providing text for the following keys: 
    
    •struts.messages.error.uploading - a general error that occurs when the file could not be uploaded
    文件上传出错的消息 •struts.messages.error.file.too.large
    - occurs when the uploaded file is too large 文件超过最大值的消息 •struts.messages.error.content.type.not.allowed - occurs when the uploaded file does not match the expected content types specified 文件内容不合法的消息 •struts.messages.error.file.extension.not.allowed - occurs when the uploaded file does not match the expected file extensions specified
    文件扩展名不合法的消息

    可以参考 org.apache.struts2. 下的 struts-message.properties ,可提供更多的定制信息

    在 org.apache.struts2. 下的 default.properties 中有对文件上传总的大小的限制。可以使用常量的方式,修改限制:struts.multipart.maxSize = ?

     1  1 <!-- 配置国际化资源文件 -->
     2  2      <constant name="strut2.custom.i18n.resouce" value="i18n"></constant>
     3  3      
     4  4      <constant name="struts.action.extension" value="action,do,"></constant>
     5  5      
     6  6      <package name="default" namespace="/" extends="struts-default">
     7  7      
     8  8          <interceptors>
     9  9              <interceptor-stack name="jasonStack">
    10 10                  <interceptor-ref name="defaultStack">
    11 11                      <param name="fileUpload.maximumSize">2000</param>
    12 12                      <param name="fileUpload.allowedTypes">text/html,text/xml</param>
    13 13                      <param name="fileUpload.allowedExtensions">html,ppt,xml</param>
    14 14                  </interceptor-ref>
    15 15              </interceptor-stack>
    16 16          </interceptors>
    17 17          
    18 18          
    19 19          <default-interceptor-ref name="jasonStack"></default-interceptor-ref>
    20 20          <action name="testUpload" class="com.jason.upload.app.UploadAction">
    21 21              <result>/sucess.jsp</result>
    22 22          </action>
    23 23          
    24 24      </package>
    25 25  
    struts.xml
    1 struts.messages.error.uploading=u6587u4EF6u4E0Au4F20u51FAu9519u7684u6D88u606F
    2 struts.messages.error.file.too.large=u6587u4EF6u8D85u8FC7u6700u5927u503Cu7684u6D88u606F
    3 struts.messages.error.content.type.not.allowed=u6587u4EF6u5185u5BB9u4E0Du5408u6CD5u7684u6D88u606F
    4 struts.messages.error.file.extension.not.allowed=u6587u4EF6u6269u5C55u540Du4E0Du5408u6CD5u7684u6D88u606F
    i18n.properties

    2.文件的下载

      1)struts2 中使用 type="stream" 的result 进行下载即可:具体细节 /struts-2.3.15.3-all/struts-2.3.15.3/docs/WW/docs/stream-result.html

      2)Struts 专门为文件下载提供了一种 Stream 结果类型. 在使用一个 Stream 结果时, 不必准备一个 JSP 页面.

      3)Stream 结果类型可以设置如下参数:(以下参数可以在Action中以 getter 方法的方式提供)

          - contentType:被下载的文件的 MIME 类型。默认值为 text/plain

          - contentLength:被下载的文件的大小,以字节为单位

          - contentDisposition: 可以设置下载文件名的ContentDispositon 响应头,默认值为 inline,通常设置为如下格式: attachment;filename="document.pdf".

          - inputName:Action 中提供的文件的输入流。默认值为 inputStream

          - bufferSize:文件下载时缓冲区的大小。默认值为 1024

          - allowCaching :文件下载时是否允许使用缓存。默认值为 true

          - contentCharSet:文件下载时的字符编码。

    4)Stream 结果类型的参数可以在 Action 以属性的方式覆盖

    download.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10     <a href="testDownload">Down Load</a>
    11 </body>
    12 </html>
    DownLoadAction.java
    对于
    contentType
    contentLength
    contentDisposition
    inputStream
    我们需要在对应的Action 中声明一个变量 且提供 getter方法
     1 package com.jason.upload.app;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.InputStream;
     5 
     6 import javax.servlet.ServletContext;
     7 
     8 import org.apache.struts2.ServletActionContext;
     9 
    10 import com.opensymphony.xwork2.ActionSupport;
    11 
    12 public class DownLoadAction extends ActionSupport {
    13 
    14     /**
    15      * @Fields:serialVersionUID
    16      */
    17     private static final long serialVersionUID = 1L;
    18 
    19     private String contentType;
    20     private long contentLength;
    21     private String contentDisposition;
    22     private InputStream inputStream;
    23 
    24     public String getContentDisposition() {
    25         return contentDisposition;
    26     }
    27 
    28     public long getContentLength() {
    29         return contentLength;
    30     }
    31 
    32     public String getContentType() {
    33         return contentType;
    34     }
    35 
    36     public InputStream getInputStream() {
    37         return inputStream;
    38     }
    39     @Override
    40     public String execute() throws Exception {
    41         
    42         //1.确定各成员的值
    43         contentType = "text/html";
    44         contentDisposition = "attachment;filename='a.html'";
    45         
    46         ServletContext  servletContext = ServletActionContext.getServletContext();
    47         String fileName = servletContext.getRealPath("/files/a.html");
    48         inputStream = new FileInputStream(fileName);
    49         contentLength = inputStream.available();
    50         return super.execute();
    51     }
    52 
    53 }

    struts.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 
     6 <struts>
     7 <action name="testDownload" class="com.jason.upload.app.DownLoadAction">
     8              <result type="stream">
     9                  <param name="bufferSize">2048</param>
    10              </result>
    11          </action>
    12 </package>
    13          
    14 </struts>

     

  • 相关阅读:
    Django实现自定义template页面并在admin site的app模块中加入自定义跳转链接
    django中将model转换为dict的方法
    django后台显示图片 而不是图片地址
    Django admin 继承user表后密码为明文,继承UserAdmin,重写其方法
    Android API之Telephony.Sms
    com.android.providers.telephony.MmsSmsDatabaseHelper
    在发送信息时应用PendingIntent.FLAG_UPDATE_CURRENT
    Android开发之旅(吴秦)
    Android API之android.content.BroadcastReceiver
    Receiver not registered.
  • 原文地址:https://www.cnblogs.com/jasonHome/p/5928195.html
Copyright © 2020-2023  润新知