天天看點

Struts2下載下傳中文檔案

文章出处:http://gznofeng.javaeye.com/blog/213851

 

Java代码

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.net.URLDecoder;

import org.apache.struts2.ServletActionContext;

public class DownLoadAction extends BaseAction {

private String fileName;// 初始的通过param指定的文件名属性

private String inputPath;// 指定要被下载的文件路径

public InputStream getInputStream() throws Exception {

System.out.println(getRequest().getParameter("fileName"));

// 通过 ServletContext,也就是application 来读取数据

System.out.println(fileName);

System.out.println(URLDecoder.decode(fileName));

return ServletActionContext.getServletContext().getResourceAsStream(inputPath+"//"+fileName);

}

public String execute() throws Exception {

return SUCCESS;

}

public void setInputPath(String value) {

inputPath = value;

}

public void setFileName(String fileName) {

this.fileName = fileName;

}

/** 提供转换编码后的供下载用的文件名 */

public String getDownloadFileName() {

String downFileName = fileName;

try {

downFileName = new String(downFileName.getBytes(), "ISO8859-1");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return downFileName;

}

}

XML配置:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="com.trendcom.uploadfile.action.DownLoadAction" namespace="/download" extends="struts-default">

<!-- 文件下载,支持中文附件名 -->

<action name="download"

class="com.trendcom.uploadfile.action.DownLoadAction">

<!-- 初始文件存放路径 -->

<param name="inputPath">/WEB-INF/upload/</param>

<result name="success" type="stream">

<param name="contentType">

application/octet-stream;charset=ISO8859-1

</param>

<param name="inputName">inputStream</param>

<!-- 使用经过转码的文件名作为下载文件名,downloadFileName属性

对应action类中的方法 getDownloadFileName() -->

<param name="contentDisposition">

attachment;filename="${downloadFileName}"

</param>

<param name="bufferSize">4096</param>

</result>

</action>

<!-- Add actions here -->

</package>

</struts>

 

繼續閱讀