struts2文件下载

一个简单的利用struts2做文件下载的demo…… 

首先配好struts:

web.xml 

<?xml version="1.0" encoding="UTF-8"?> 
<web-app 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"> 
<welcome-file-list> 
<welcome-file>index.jsp</welcome-file> 
</welcome-file-list> 

<filter> 
<filter-name>struts2</filter-name> 
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 
</filter> 
<filter-mapping> 
<filter-name>struts2</filter-name> 
<url-pattern>/*</url-pattern> 
</filter-mapping> 

</web-app>


struts.xml——这里是重点 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "struts-2.3.dtd">

<struts> 
<!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。 如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
    <constant name="struts.action.extension" value="action" />
        <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
    <constant name="struts.serve.static.browserCache" value="false" />
        <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
    <constant name="struts.configuration.xml.reload" value="true" />
<!-- 设置webapp为开发模式 ,开发模式下使用,这样可以打印出更详细的错误信息 -->
    <constant name="struts.devMode" value="true" />
<!-- 默认的视图主题 -->
    <constant name="struts.ui.theme" value="simple" />
<!-- 整合Spring -->
    <constant name="struts.objectFactory" value="spring"></constant>
<!-- 标示对符合此正则表达式的URL,Struts不进行过滤 仅传递 -->
    <constant name="struts.action.excludePattern" value="/ckfinder.*"/>
<!-- 设置字符集,解决乱码 -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
<!-- 配置上传文件的最大值 -->
    <constant name="struts.multipart.maxSize" value="10485760" />
<!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir" value="d:/temp" />
<!-- 指定国际化资源文件的baseName为struts-->
    <constant name="struts.custom.i18n.resources" value="struts" />
   
        <!-- package中的name只是一个标识,你可以随意命名;  -->
        <!-- class值设为了loginAction,即applicationContext.xml里的LoginAction类的bean的ID。这样我们就把LoginAction类交给了spring管理。 -->
        <!-- action中的name对应你页面中的一个action跳转,比如你页面有个表单提交: <form action="struts.xml中action里的name">  -->
        <!-- Action 元素method属性,默认值为method=”execute”,也就是当action接收到请求后,交给哪个方法去处理,默认的是交给execute方法去处理,当然,也可以交给其他方法-->
<package name="default1" namespace="" extends="json-default">
     <action name="enter" class="LoginAction" method="login">
     <result type="json">
     <param name="root">result</param>
     </result>
     </action>
     <action name="readExcel" class="LoginAction" method="readExcel">
     <result type="json">
     <param name="root">result</param>
     </result>
     </action>
    
     <action name="upload" class="UploadAction" method="fileUpload">
     <result type="json">
     <param name="root">result</param>
     </result>
           <!-- 配置拦截器限制上传文件的类型及大小 -->
        <interceptor-ref name="fileUpload">
        <param name="allowedType">image/bmp,image/x-png,image/gif,image/jpeg</param>
        <param name="maximumSize">2M</param>
        </interceptor-ref>
        <interceptor-ref name="defaultStack"></interceptor-ref>
<result type="json" name="success">
<param name="contentType">
text/html
</param>
</result>
<result type="json" name="error">
<param name="contentType">
text/html
</param>
</result>
        </action>
        
        <action name="insertdata" class="LoginAction" method="insertdata">
     <result type="json">
     <param name="root">result</param>
     </result>
     </action>
    
            <!-- 下载文件的Action -->
        <action name="download" class="DownloadAction" method="download">
        <!-- 指定被下载资源的位置 -->
                <!-- <param name="inputPath">/Html/imgs/2.jpg</param> -->

     <!-- 配置结果类型为stream的结果 -->
     <result name="success" type="stream">
              <!-- 动态文件下载的,事先并不知道未来的文件类型,那么我们可以把它的值设置成为:application/octet- stream;charset=ISO8859-1 ,注意一定要加入charset,否则某些时候会导致下载的文件出错; -->
      <!-- contentType 指定下载文件的文件类型 ——application/octet-stream 表示无限制 -->
             <param name="contentType">application/octet-stream;charset=ISO8859-1</param>
                 <!-- inputName 流对象名 ——比如这里写inputStream,它就会自动去找Action中的getInputStream方法。  -->
             <param name="inputName">inputStream</param>
         <!-- contentDisposition 使用经过转码的文件名作为下载文件名 ——默认格式是attachment;filename="${fileName}",将调用该Action中的getFileName方法。  -->
         <!-- attachment;filename="struts2.txt",表示文件下载的时候保存的名字应为struts2.txt。如果直接写filename="struts2.txt",那么默认情况是代表inline,浏览器会尝试自动打开它,等价于这样的写法:inline; filename="struts2.txt" -->
 <!-- contentDisposition 使用经过转码的文件名作为下载文件名 ——默认格式是attachment;filename="${fileName}",将调用该Action中的getFileName方法。  -->
             <param name="contentDisposition">attachment;filename="${fileName}"</param>
                 <!-- 指定下载文件的缓冲大小 -->
             <param name="bufferSize">50000000</param>
     </result>
     </action>
    </package>

1)  <param name="contentDisposition">attachment;fileName="${fileName}"</param>

     contentDisposition默认是 inline(内联的), 比如说下载的文件是文本类型的,就直接在网页上打开,不能直接打开的才会打开下载框自己选择

2)  attachment :下载时会打开下载框

3)  fileName="${fileName}" :在这定义的名字是一个动态的,该名字是显示在下载框上的文件名字

4.<param name="inputName">downloadFile</param>,这个downloadFile名字要和FileDownload.java类中的getDownloadFile()方法名去掉get 一致

当result为stream类型时,struts2会自动根据你配置好的参数下载文件。 

接着在DownloadAction里新建download方法,

package com.xhgjky.ssh.action;

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private String fileName; 

public String getFileName() {
return ServletActionContext.getRequest().getParameter("fileName");
}
public void setFileName(String fileName) {
try {
fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");
//对接受的中文文件名进行转码,否则找不到文件所在的输出流
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("转码失败!!");
}
this.fileName = fileName;
}

public InputStream getInputStream() {
fileName = "哈.xls";
System.out.println(fileName);
InputStream is=ServletActionContext.getServletContext().getResourceAsStream("/Html/upload/" + fileName);
System.out.println("is:"+is);
return is;
}

public String download(){
System.out.println("download..");
return SUCCESS;
}
}

* 注意使用getResourceAsStream方法时,文件路径必须是以“/”开头,且是相对路径。这个路径是相对于项目根目录的。 
* 可以用return new FileInputStream(fileName)的方法来得到绝对路径的文件。 

在WEB-INF下随意丢一个test.txt,部署好后进入浏览器,输入tomcat地址/项目路径/download.action?fileName=test.txt即可下载到该文件。 


你可能感兴趣的:(文件下载,struts2)