不多说,直接上具体代码:
action中的代码:
public class Action extends ActionSupport {
//下载文件
private String res; //文件源
private String resName;//文件名
private String resType;//文件类型
....(get/set方法)
//文件下载
public InputStream getTarget() throws FileNotFoundException
{ //这个路径源 视自己情况而定 ,注意,如果下载出错,很有可能就是路径不对,可以调试的时候打印路径查看
String path=ServletActionContext.getServletContext().getRealPath("/file")+"\\"+res;
return new FileInputStream(path);
}
public String fileDownload()
{
return SUCCESS;
}
}
struts中的配置
<action name="fileDownload" class="com.action.Action" method="fileDownload">
<result type="stream">
<!-- 二进制流类型 -->
<param name="contentType">${resType}</param>
<!--指定返回inputStream方法 填写那个getTarget方法 去掉get 同时将T小写 -->
<param name="inputName">target</param>
<param name="contentDisposition">attachment;filename=${resName}</param>
<param name="bufferSize">1024</param>
</result>
</action>
jsp页面中的配置
<a href="fileDownload.action?resType=text/plain
&res=<s:property value="request[0].urlfile"/>&resName=下载文件.txt"><s:property value="request[0].urlfile"/></a>
其中的resType的类型我的是txt,不同文件类型不一样,可以网上查查,其中的request[0].urlfile是我具体需求而定,这个更具自己实际情况只要将res,resname,resType传递过去就可