`
hehebendan
  • 浏览: 81756 次
  • 性别: Icon_minigender_1
  • 来自: 伊拉克
社区版块
存档分类
最新评论

struts2的文件上传与下载

阅读更多

针对与struts2的文件上传与下载是非常简单的。对于upload来讲:struts2在defaultStack这个拦截器栈已经提供了支持了,对于upload来说大致一个完成过程如下:

1)书写JSP,上传数据的时候要记得form的method为post,enctype为multipart/form-data

2)书写action: 配置file,fileFiileName,fileContentType. struts2帮我们封装文件名,与文件类型。分别为他们提供setter和getter方法.

3)execute方法的书写简单的代码如下:

public String execute() throws Exception {
		// TODO Auto-generated method stub
		FileInputStream inputStream = new FileInputStream(file);
		String path  = ServletActionContext.getRequest().getRealPath("/upload");
	    System.out.println(path);
		FileOutputStream out = new FileOutputStream(new File(path,this.getFileFileName()));
        int length = 0;
        byte [] buffer = new byte[1024];
        while((length=inputStream.read(buffer))!=-1){
        	out.write(buffer,0,length);
        	out.flush();
        }
        out.close();
        inputStream.close();
		return SUCCESS;
	}

 

我们打开struts-default.xml这个配置文件,有如下代码片段:

  <interceptors>
            <interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
            <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
            <interceptor name="chain" class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/>
            <interceptor name="conversionError" class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>
            <interceptor name="cookie" class="org.apache.struts2.interceptor.CookieInterceptor"/>
            <interceptor name="clearSession" class="org.apache.struts2.interceptor.ClearSessionInterceptor" />
            <interceptor name="createSession" class="org.apache.struts2.interceptor.CreateSessionInterceptor" />
            <interceptor name="debugging" class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />
            <interceptor name="externalRef" class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor"/>
            <interceptor name="execAndWait" class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/>
            <interceptor name="exception" class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>
            <interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>
            <interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>
            <interceptor name="logger" class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/>
            <interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
            <interceptor name="scopedModelDriven" class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/>
            <interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>
            <interceptor name="actionMappingParams" class="org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/>
            <interceptor name="prepare" class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/>
            <interceptor name="staticParams" class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>
            <interceptor name="scope" class="org.apache.struts2.interceptor.ScopeInterceptor"/>
            <interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
            <interceptor name="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/>
            <interceptor name="timer" class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>
            <interceptor name="token" class="org.apache.struts2.interceptor.TokenInterceptor"/>
            <interceptor name="tokenSession" class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>

 可以看见一个fileUpload的拦截器。我们打开这个拦截器的源代码:如下:

public class FileUploadInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = -4764627478894962478L;

    protected static final Log log = LogFactory.getLog(FileUploadInterceptor.class);
    private static final String DEFAULT_DELIMITER = ",";
    private static final String DEFAULT_MESSAGE = "no.message.found";

    protected Long maximumSize;
    protected String allowedTypes;
    protected Set allowedTypesSet = Collections.EMPTY_SET;

    /**
     * Sets the allowed mimetypes
     *
     * @param allowedTypes A comma-delimited list of types
     */
    public void setAllowedTypes(String allowedTypes) {
        this.allowedTypes = allowedTypes;

        // set the allowedTypes as a collection for easier access later
        allowedTypesSet = getDelimitedValues(allowedTypes);
    }

    /**

 可以看见一些成员变量,表示上传文件的最大size以及允许上传的文件类型。需要说明的是最大容量的现在是以字节为单位的,文件类型也不是文件的后缀名:例如.txt文件他的文件类型应该是:text/plain。这些都可以在tomcat的web.xml文件中找到。 下面我们将刚刚的两个属性配置到xml文件中去:配置如下:

   <action name="upload" class="com.wh.struts2.action.FileUploadAction">
         <result name="success">/index.jsp</result>
         <interceptor-ref name="fileUpload">
           <param name="maximumSize">5242880</param>
           <param name="allowedTypes">text/plain</param>
         </interceptor-ref>
         <interceptor-ref name="defaultStack"></interceptor-ref>
       </action>

 

这里需要的注意到是当你应该了一个单独的拦截器之后,struts2就不会在去附加默认的拦截器了,因此我们还需要手动的在引用一次默认拦截器栈。

 

二) 文件的下载:

1)简单的不能在简单的JSP:

<body>
     <a href="downLoad.action">下载</a>
  </body>

 2)简单的action:

package com.wh.struts2.action;

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownLoadAction extends ActionSupport {
	public InputStream getInputStream(){
		return ServletActionContext.getServletContext().getResourceAsStream("/upload/spring.doc");
	}
    @Override
    public String execute() throws Exception {
    	// TODO Auto-generated method stub
    	return SUCCESS;
    }
}

 3)简单的配置:

 <action name="downLoad" class="com.wh.struts2.action.DownLoadAction">
          <result type="stream" name="success">
            <param name="contentType">application/msword</param>
            <param name="contentDisposition">filename="spring.doc"</param>
            <param name="inputName">inputStream</param>
          </result>
       </action>

 对于文件的下载,在action需要提供一个返回一个输入流的方法,方法名可以任意的。应该满足PO的书写规范。配置xml文件的时候inputName的值,就是刚刚提供的方法的名称。 文件下载的时候type必须是stream,那么这些配置的属性又是如何找到的?  同样是struts-default.xml,有如下片段:

   <result-types>
            <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>
            <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>
            <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
            <result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>
            <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>
            <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>
            <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
            <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>
            <result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>
            <result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />
        </result-types>

 

我们可以看见结果类型中有个对于stream。我们查看下这个类的原代码:

 

public class StreamResult extends StrutsResultSupport {

    private static final long serialVersionUID = -1468409635999059850L;

    protected static final Log log = LogFactory.getLog(StreamResult.class);

    public static final String DEFAULT_PARAM = "inputName";

    protected String contentType = "text/plain";
    protected String contentLength;
    protected String contentDisposition = "inline";
    protected String inputName = "inputStream";
    protected InputStream inputStream;
    protected int bufferSize = 1024;

    public StreamResult() {
        super();
    }

    public StreamResult(InputStream in) {
        this.inputStream = in;
    }

    /**

 

就可以看见配置的文件是哪里的了吧。 呵呵,简单的介绍到这里了。

 

 

分享到:
评论

相关推荐

    struts2文件上传与下载

    在Struts2中,文件上传和下载是常见的功能需求,主要用于处理用户在Web表单中提交的文件,如图片、文档等。下面将详细介绍Struts2中文件上传和下载的实现方法。 ### 1. 文件上传 #### 1.1 配置Struts2 首先,我们...

    Struts2文件上传与下载

    Struts2是一个强大的Java web框架,它为开发者提供了丰富的功能,包括处理用户表单提交、进行文件上传和下载。在Web应用中,文件上传和下载是常见的需求,例如用户上传头像、下载文档等。Struts2通过其Action类和...

    struts2 文件上传与下载

    在这个主题“Struts2文件上传与下载”中,我们将深入探讨如何在Struts2框架中实现文件的上传和下载功能,这对于创建交互式的Web应用是至关重要的。 文件上传允许用户通过Web表单提交文件到服务器,而文件下载则是将...

    struts2文件上传下载源代码

    在Struts2中,文件上传和下载是常见的功能需求,特别是在处理用户交互和数据交换时。这篇博客文章提供的"struts2文件上传下载源代码"旨在帮助开发者理解和实现这些功能。 文件上传功能允许用户从他们的设备上传文件...

    struts2实现文件上传下载

    本篇文章将详细探讨如何在Struts2框架下实现文件的上传与下载。 首先,我们需要了解Struts2中的文件上传机制。Struts2提供了`FileUploadInterceptor`拦截器来处理文件上传请求。在处理文件上传时,开发者需要在...

    struts2文件上传和下载

    在Struts2中,文件上传和下载是常见的功能需求,对于用户交互和数据交换至关重要。以下是对这些知识点的详细阐述: 1. **文件上传**: 在Struts2中,文件上传主要依赖于`Commons FileUpload`库,它是一个Apache提供...

    Struts2文件上传和下载教程

    ### Struts2文件上传与下载教程 #### 一、文件上传原理及实现 **1.1 基础概念** 文件上传是Web开发中的常见需求之一。在Struts2框架中,实现文件上传主要依赖于表单的`enctype`属性设置为`multipart/form-data`。...

    struts2文件上传下载

    在这个特定的项目中,我们关注的是"struts2文件上传下载"的功能,这涉及到用户通过Web界面上传文件到服务器,以及从服务器下载文件到用户的设备。 文件上传是Web应用中的常见需求,例如用户可能需要提交图片、文档...

    struts与hibernate实现文件的上传与动态下载

    通过以上步骤,你可以实现一个基于Struts2和Hibernate的文件上传与动态下载系统。这个系统能够处理用户上传的文件,将其保存到服务器,同时提供动态下载功能,允许用户根据需要下载文件。在实际开发中,还需要考虑...

    struts2文件上传与下载源码-包含超出指定文件大小提示

    struts2文件的上传与下载,包含超出指定文件大小之后的提示。更多详细内容,请参考博客:http://blog.csdn.net/qq_20889581/article/details/52838848

    struts2文件上传jar

    这个压缩包包含了实现Struts2文件上传所需的全部jar包,这些库文件对于理解和实现文件上传功能至关重要。 首先,我们要了解Struts2文件上传的基本流程。当用户通过表单提交包含文件输入字段的请求时,Struts2框架会...

    Struts2之struts2文件上传详解案例struts011

    在Struts2中,文件上传功能是常见的需求,比如用户可能需要上传个人照片、文档或者其他类型的文件。在这个"Struts2之struts2文件上传详解案例struts011"中,我们将深入探讨如何实现这一功能。 首先,我们需要了解...

    Struts2多文件上传下载实例

    在实际项目中,文件上传和下载功能是必不可少的,本实例将详细讲解如何在Struts2框架下实现单个文件及多个文件的上传与下载。 首先,我们需要在Struts2的配置文件(struts.xml)中添加相关的Action配置,以便处理文件...

    struts2 文件上传

    struts2 文件上传 struts2上传标签file fileuploadstruts2 文件上传 struts2上传标签file fileuploadstruts2 文件上传 struts2上传标签file fileupload

    Struts2文件上传下载.docx

    ### Struts2 文件上传与下载实现详解 #### 一、简介 在Web开发中,文件的上传和下载是非常常见的需求之一。Struts2框架作为Java Web开发中的一个重要框架,提供了非常方便的方式来处理这类操作。本文将详细介绍如何...

    struts实现的文件上传下载功能

    在这个特定的场景中,我们关注的是如何使用Struts来实现文件的上传和下载功能。这个功能对于任何Web应用来说都是非常重要的,因为它允许用户交互地处理数据和资源。 首先,我们需要理解文件上传的基本流程。在...

Global site tag (gtag.js) - Google Analytics