struts2的文件下传与上载

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;
    }

    /**

 

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