struts文件下载

来源:互联网 发布:网络发票管理系统下载 编辑:程序博客网 时间:2024/05/22 00:31

在webroot下有个文件夹file要下载里面的文件



首先访问download_list,通过DownLoadAction的list()方法把文件信息显示在list.jsp

public String list(){String path = ServletActionContext.getServletContext().getRealPath("/file");File file=new File(path);//获取所有文件名String[] fileNames=file.list();//存入request域,转发到list.jspMap<String, Object> request=ActionContext.getContext().getContextMap();request.put("fileNames", fileNames);return "success";}
<table border="1">   <tr>   <td>编号</td>   <td>文件名</td>   <td>操作</td>   </tr>   <c:forEach var="fileName" items="${fileNames}" varStatus="vs">   <tr>   <td>${vs.count}</td>   <td>${fileName}</td>   <td>   <c:url var="url" value="download_down">   <c:param name="fileName" value="${fileName }"></c:param>   </c:url>   <a href="${url}">下载</a>   </td>   </tr>   </c:forEach>   </table>
上面是jsp显示效果如下


下面是在DownLoadAction中的处理下载的方法

//1.获取要下载的文件的文件名private String fileName;public String getFileName() {return fileName;}public void setFileName(String fileName) {//处理传入的参数问题try {fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");this.fileName = fileName;} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}}
//2.下载提交的业务方法public String down(){return "download";}
//3.返回文件流的方法public InputStream getAttrInputStream(){return ServletActionContext.getServletContext().getResourceAsStream("/file/"+fileName);}
//4.告诉浏览器显示的文件名public String getDownFileName(){try {fileName = URLEncoder.encode(fileName,"UTF-8");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}return  fileName;}







0 0
原创粉丝点击