Servlet 下载文件代码

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    
    private static final int BUFSIZE = 4096;
    String filePath = null;
  
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
  
        filePath = getServletContext().getRealPath("") + File.separator + "abc.txt";
         
        File file = new File(filePath);
        int length = 0;
        ServletOutputStream outStream = response.getOutputStream();
        response.setContentType("text/html");
        response.setContentLength((int) file.length());
        String fileName = (new File(filePath)).getName();
        response.setHeader("Content-Disposition", "attachment; filename=\""+ fileName + "\"");
  
        byte[] byteBuffer = new byte[BUFSIZE];
        DataInputStream in = new DataInputStream(new FileInputStream(file));
  
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }
  
        in.close();
        outStream.close();
    }
 
}