您的位置:首页 > 其它

strut2文件下载及注意事项

2012-11-25 18:03 267 查看
不多说话,直接上代码:

文件保存在项目Test的根目录的resource文件夹下

Action代码:

......
public class DownLoad extends ActionSupport{
public String downLoad(){
return SUCCESS;
}

public InputStream getInputStream throws Exception{

String path="/resource/test_store.txt";   //这个路径是相对于工程根目录的绝对路径,注意不要写错了,否则会抛出如下异常,本人亲自试过:
//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(path);
}
......


struts.xml配置信息:

......
<action name="download.*" class="com.system.action.DownLoad" method="downLoad">
<result name="success" type="stream">
<!--如果系统会自动到你的action中去找getInputStream方法;也可以为其他名称,但相应的方法名称也要改-->
<param name="inputName">inputStream</param>
<param name="bufferSize">4096</param>
<!--  attachment的意思是直接下载,不让浏览器自动打开;filename指定下载文件的文件名,就是你在文件下载对话框中看到的文件名  -->
<param name="contentDisposition">attachment:filename="text_save.txt"</param>
</result>
</action>
......


然后通过浏览器访问download.action就可以下载到text_store.txt

<--完-->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: