public class DownLoadAction extends ActionSupport
{
private String downPath; // 下载时的文件名
private String contentType; // 保存文件类型
private String filename; // 保存时的文件名
private String directory = "";
public String getDirectory()
{
return directory;
}
public void setDirectory(String directory)
{
this.directory = directory;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getDownPath() {
return downPath;
}
public void setDownPath(String downPath) {
try {
// 解决下载时候的中文文件乱码问题
downPath = new String(downPath.getBytes("ISO-8859-1"),"UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
this.downPath = downPath;
}
/*
*下载用的Action返回一个InputString实例,该方法对应Action配置
*里面的result的inputName参数,值为inputString
*
*/
public InputStream getInputStream(){
//directory+"/"+downPath路径一定要正确,否则会报错
//Exception occurred during processing request: Can not find a java.io.InputStream with the name [inputStream] in the invocation stack.
//Check the <param name="inputName"> tag specified for this action.
return ServletActionContext
.getServletContext().getResourceAsStream(directory+"/"+downPath);
}
public String execute(){
// 下载保存时的文件名和被下载的文件名一样
filename = downPath;
// directory必须是工程下的文件夹
downPath = directory+"/"+downPath;
// 保存文件的类型
log.info("directory="+directory+" filename="+filename+" downPath="+downPath);
contentType = "application/octet-stream";
return SUCCESS;
}
}
struts.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="download" extends="struts-default" namespace="/download">
<action name="DownLoadAction" class="download.action.DownLoadAction">
<result type="stream">
<param name="contentType">${contentType}</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename=${filename}</param>
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>
jsp
<a href="/download/DownLoadAction.action?downPath="文件名">文件名</a>