不多說,直接上具體代碼:
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傳遞過去就可