struts文件下载

    xiaoxiao2026-05-26  4

    在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.jsp Map<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 block e.printStackTrace(); } return fileName; }

    转载请注明原文地址: https://ju.6miu.com/read-1310092.html
    最新回复(0)