struts2 文件下载---简单明了

来源:互联网 发布:黄岩深孔钻编程招聘 编辑:程序博客网 时间:2024/06/05 02:12

不多说,直接上具体代码:

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传递过去就可







原创粉丝点击