1.页面
<ahref="downAction?filename=要下载的文件名">要下载的文件名</a>
2.DownAction
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 DownAction extends ActionSupport {
private String filename;
public String getFilename() {
return filename;
}
public void setFilename(Stringfilename) {
try {
this.filename = newString(filename.getBytes("ISO-8859-1"),"UTF-8");
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public InputStream getInputStream(){
HttpServletResponse response =ServletActionContext.getResponse();
try {
response.setHeader("Content-Disposition","attachment;fileName="+java.net.URLEncoder.encode(filename,"UTF-8"));
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
return ServletActionContext.getServletContext().
getResourceAsStream("/up/"+filename);
}
@Override
public String execute() throws Exception {
System.err.println("InputStream:"+getInputStream()); 此处最好打印以下测试看看是否获取到输出流
System.err.println("下载:" + getFilename()+">>>>>>"+ServletActionContext.getServletContext().
getRealPath(getFilename()));
return SUCCESS;
}
}
3.struts.xml
<package name="user" extends="struts-default"namespace="/">
<!—-引用拦截器 -->
<default-interceptor-ref name="defaultStack"></default-interceptor-ref>
<action name="downAction" class="czb.hr.user.action.DownAction">
<result name="success" type="stream">
<!-- 调用getFile方法 -->
<param name="inputName">InputStream</param>
<!-- 以下会下载图片,注意第一个参数 -->
<param name="contentDisposition">attachment;filename="${filename}"</param>
<param name="bufferSize">4096</param>
</result>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</action>
</package>