下载txt文件

来源:互联网 发布:js键盘事件代码 编辑:程序博客网 时间:2024/04/25 00:27
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
//      String filename = request.getParameter("filename");//"1a.txt";   
//      String filepath = request.getParameter("filepath");//"d:\\";
//       System.out.println(filename);
//      System.out.println(filepath);
   String filepath=request.getSession().getServletContext().getRealPath("");
   System.out.println("===jia"+filepath);
   filepath=filepath+"\\fileUpload\\default\\mail\\";
   String filename="2.xls";
       File file=new File(filepath+filename);
      if(!file.exists()){
       response.sendError(404, "没有找到资源Rain Rocky");
      }
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            //response.setContentType("image/bitmap");
            //下面这句 点击连接时 提供下载提示;没有这句的话  点击连接在窗口中打开资源
            response.setHeader("Content-Disposition","attachment;filename ="+filename);
      try{
       InputStream is = new FileInputStream(file);
       BufferedInputStream bis=new BufferedInputStream(is);
       BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
       byte[] buff = new byte[2048];
       int i = 0;
      while((i= bis.read(buff,0,buff.length)) != -1){
      
       
        out.write(buff,0,i);  
        }
        out.close();
        bis.close();
      }catch (Exception e) {
   
  }
 }