首先action
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadFile extends ActionSupport {
private String fileName;
private String savePath = "/upload";
public String getFileName() {
return fileName;
}
public void setFileName(String fileName)
throws UnsupportedEncodingException {
this.fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
// 中文支持设置
}
public InputStream getInputStream() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setHeader("Content-Disposition", "attachment;fileName="
+ java.net.URLEncoder.encode(fileName, "UTF-8"));
/**
* 上面两句是实现中文支持
*/
String dir = savePath + "/" + fileName;
InputStream in = ServletActionContext.getServletContext()
.getResourceAsStream(dir);
return in;
/**
* 如果你遇到java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name
[inputStream] in the invocation stack. Check the tag specified for this action.
*
* 恭喜你,你的路径可能错误,得到的in为null。
*
* 如果dir是绝对路径
* return new FileInputStream(dir);
* 如果dir是Resource下的相对路径
* return ServletActionContext.getServletContext().getResourceAsStream(dir);
*/
}
public String execute() throws Exception {
return SUCCESS;
}
}
struts 配置:
<action name="downLoad" class="DownloadFile">
<!-- 要注意result的类型是stream -->
<result name="success" type="stream">
<!-- inputName参数指定文件的源头,根据这个配置,找getDownloadFile方法获得文件流 -->
<param name="inputName">inputStream</param>
<!-- 指定下载的方式,默认的是inline,这种方式,浏览器如果能打开的文件的话,就直接打开,而不会下载(如.txt格式文件)。一般指定是attachment方式,让用户可以选择是打开还是下载。 -->
<!-- 如果像这样,action里必须提供fileName的get方法 ,当然你也可以给定好。-->
<param name="contentDisposition">
attachment;fileName="${fileName }"
</param>
<!-- 还可以指定文件的格式,缓冲大小 -->
<param name="bufferSize">2048</param>
</result>
</action>
jsp页面:
<a href="downLoad.action?fileName=${fileName }">${fileName }"</a>
参考博文: struts2实现文件的上传、下载, struts2文件下载出现Can not find a java.io.InputStream with the name的错误 , JSP、Struts2下载中文文件名乱码问题处理。