struts2.0文件下载

来源:互联网 发布:linux脚本编程 编辑:程序博客网 时间:2024/05/21 08:07

struts.xml配置

<action name="downLoad" class="com.hdz.base.action.UploadAction" method="downLoad">
     <result name="success" type="stream">
         <!-- 指定下载文件的内容类型,text/plain是默认类型 -->
         <param name="contentType">text/plain</param >
         <!-- inputName默认值是inputStream,如果action中用于读取下载文件内容的属性名是inputStream,那么可以省略这个参数 -->
         <param name="inputName">inputStream</param>
         <!--动态获取文件名,从Action中的取得filename-->
         <param name="contentDisposition">
             attachment;filename="${downloadFileName}"
         </param>
         <param name="bufferSize">2048</param>
     </result>
 </action>

action配置

public String downLoad(){
  return SUCCESS;
 }
 public InputStream getInputStream() throws Exception {
        String dir = "d:\\upload\\" + filename;
        File file = new File(dir);
        InputStream is = new FileInputStream(file);
        //return ServletActionContext.getServletContext().getResourceAsStream("/upload/31.jpg");//如果是相对路径
        return is;    //如果dir是绝对路径
 }

//处理中文文件名
 public String getDownloadFileName() {
  String downFileName = filename;
  try {
  downFileName = new String(downFileName.getBytes(), "ISO8859-1");
  } catch (UnsupportedEncodingException e) {
  e.printStackTrace();
  }
  return downFileName;
  }