Downfile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <%@page import="java.io.*" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Downfile.jsp' starting page</title> <style type="text/css"> a:hover{color:red;} </style> </head> <body> <center> <font color="#00008b" size="5" >文件下载站</font><br><br> <table> <% path=request.getRealPath(""); File file=new File(path,"\\myfile"); String str[]=file.list(); for(int i=0;i<str.length;i++){ String s=str[i]; out.print("<tr><td>"+s+"</td><td><a href='file/Downfile1.jsp?name="+s+"'>下载</a></td></tr>"); } %> </table> </center> </body> </html>
Downfile1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <%@page import="java.io.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Downfile1.jsp' starting page</title> </head> <body> <% response.reset(); try { String str = request.getParameter("name"); //第一个参数为要解码的字节字符,第二个参数为解码方法 //getBytes()里面的参数为str原来的编码方式 str = new String(str.getBytes("UTF-8"), "UTF-8"); path = request.getRealPath(""); out.print(path); path = path.substring(0, path.lastIndexOf("\\")); out.print(path); path = path + "\\myfile\\"; //第一个参数为路径,第二个参数文件名 File fileLoad = new File(path, str); response.reset(); OutputStream o = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(o); //输出文件用的字节数组,每次发送500个字节到输出流 byte b[] = new byte[500]; //客户端使用保存文件的对话框 response.setHeader( "Content-disposition", "attachment;filename=" + new String(str.getBytes("UTF-8"), "UTF-8")); //通知客户文件的MIMIE类型 response.setContentType("application/x-tar"); long fileLength = fileLoad.length(); String length = String.valueOf(fileLength); response.setHeader("Content_length", length); FileInputStream in = new FileInputStream(fileLoad); int n = 0; while ((n = in.read(b)) != -1) { bos.write(b, 0, n); } bos.close(); //java.lang.IllegalStateException: getOutputStream() has already been called for this response //加入下面两句不会抛出异常,取消response.reset(),否则会抛出 //java.lang.IllegalStateException: Cannot call reset() after response has been committed out.clear(); out=pageContext.pushBody(); } catch (Exception e) { System.out.print(e); } //response.reset(); %> </body> </html>