strut2文件下载及注意事项

来源:互联网 发布:景观怎么建模好看知乎 编辑:程序博客网 时间:2024/04/30 13:38

        不多说话,直接上代码:

        文件保存在项目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

<--完-->