基于Struts2文件下载

struts.xml文件配置:↓



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
    <struts>
      <constant name="struts.i18n.encoding" value="utf-8" />
      <constant name="struts.serve.static.browserCache" value="false" />
      <constant name="struts.devMode" value="true"/>
      <constant name="struts.configuration.xml" value="true" />
      <constant name="struts.objectFactory" value="spring"/>
      <package name="default" namespace="/" extends="struts-default">
        <!-- 这里将action扔个spring管理 -->
        <action name="down" class="download">
                                 
           <result type="stream">
           <!-- 下载的文件类型,视图页面对应的类型可以通过tomcat里的web.xml搜索相应的文件类型 -->
          <!--通过ognl表达式读取业务控制器Action的属性-->
             <param name="contentType">${resType}</param>
             <!-- 下载文件的关键返回方法 get方法 -->
             <param name="inputName">inp</param>
             <!-- 自定义被下载的文件名 -->
             <param name="contentDispostion">fileName=${resName}</param>
                                       
           </result>
        </action>
                                
        <action name="*">
         <result>/WEB-INF/view/{1}.jsp</result>
        </action>
      </package>
    </struts>


DownloadAction.java↓


package com.ssh4.download;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class DownloadAction extends ActionSupport {
  private String res;    //资源文件,
  private String resName;  //自定义被下载的文件名;
  private String resType;  //文件类型
public String getRes() {
    return res;
}
public void setRes(String res) throws UnsupportedEncodingException {
      //处理中文资源文件
        this.res = new String(res.getBytes("iso-8859-1"),"utf-8");
}
public String getResName() {
    return resName;
}
public void setResName(String resName) {
    this.resName = resName;
}
public String getResType() {
    return resType;
}
public void setResType(String resType) {
    this.resType = resType;
}
//下载文件必须有此方法
public InputStream getInp() throws FileNotFoundException{
    //资源文件的路径
    String path = ServletActionContext.getServletContext().getRealPath("/") +"WEB-INF\\download\\"+ res;
    System.out.println(path);
    return new FileInputStream(path);
                 
 }
}


你可能感兴趣的:(download)