Servlet实现文件下载的核心代码: import javax.servlet. * ; import javax.servlet.http. * ; import java.io. * ; import java.util. * ; public class DownLoadFileServlet extends HttpServlet ... { public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException ...{ String password = req.getParameter("password"); if((!checkPassword(password))||(password==null)) ...{ //指定内容类型,并且可显示中文 res.setContentType("text/html;charset=gb2312"); //取得要在响应中输出的文本流,即标准的html PrintWriter out = res.getWriter(); //输出页面头部信息 out.println("<head><title>下载信息</title></head>"); out.println("<H1 align='center'>你输入的注册码不正确</H1><hr>"); } else ...{ long totalSize = 0; //取得要传输的文件,实际应用时可以将文件路径以参数的形式传入 File f = new File("D:/Program Files/Tomcat 5.0/webapps/ROOT/WEB-INF/classes/sample.pdf"); long filelength = f.length(); byte[] b = new byte[1024]; //设置文件输出流 FileInputStream fin = new FileInputStream(f); DataInputStream in = new DataInputStream(fin); //设置响应头信息,让下载的文件显示保存信息 res.setHeader("Content-disposition", "attachment;filename=" + "sample.pdf"); //设置输出流的MIME类型 res.setContentType("application/pdf"); //确定长度 String fileSize = Long.toString(filelength); //设置输出文件的长度 res.setHeader("Content-Length",fileSize); //取出输出流 ServletOutputStream servletOut = res.getOutputStream(); //发送文件数据,每次1024字节,最后一次单独计算 while(totalSize<filelength) ...{ totalSize += 1024; if(totalSize>filelength) ...{ //最后一次传送的字节数 byte[] leftpart = new byte[1024-(int)(totalSize-filelength)]; in.readFully(leftpart);//读入字节数组 servletOut.write(leftpart);//写入输出流 } else ...{ in.readFully(b);//读入1024个字节到字节数组b servletOut.write(b);//写出输出流 } } servletOut.close(); } } /**//*public static void main(String[] args) { System.out.println("Hello World!"); }*/ //验证注册信息,在实际应用时可以换成到数据库中的验证 private boolean checkPassword(String s) ...{ String[] passwords = ...{"aaa","bbb","ccc","ddd","eee", "fff","ggg","hhh","lll","mmm"}; boolean flag = false; for (int i=0;i<passwords.length ;i++ ) ...{ if(s.equals(passwords[i])) ...{ flag = true; break; } } return flag; } public void init(ServletConfig cfg) throws ServletException ...{ super.init(cfg); } public void destroy() ...{ super.destroy(); }}