1 public void downloadTmp(HttpServletRequest request,HttpServletResponse response){ 2 try { 3 request.setCharacterEncoding("UTF-8"); 5 //第一步:设置响应类型 6 response.setContentType("application/force-download");//应用程序强制下载 7 //第二读取文件 8 String path = request.getServletContext().getRealPath(File.separator+"source"+File.separator+"tmp.txt"); 9 InputStream in = new FileInputStream(path); 10 //设置响应头,对文件进行url编码 11 //name = URLEncoder.encode(name, "UTF-8"); 12 response.setHeader("Content-Disposition", "attachment;filename=tmp.txt"); 13 response.setContentLength(in.available()); 14 15 OutputStream out = response.getOutputStream(); 16 byte[] b = new byte[1024]; 17 int len = 0; 18 while((len = in.read(b))!=-1){ 19 out.write(b, 0, len); 20 } 21 out.flush(); 22 out.close(); 23 in.close(); 24 }catch (Exception e){ 25 e.printStackTrace(); 26 } 27 }