1 public static void responseDownloadFile(HttpServletRequest request, HttpServletResponse response, File file) throws Exception { 2 if(file != null && file.length() > 0){ 3 response.setContentType("x-download;charset=UTF-8"); // 显示文件类型 Microsoft Excel 逗号分隔值文件 4 // response.setContentType("text/html;charset=UTF-8"); // 显示文件类型 360 Chrome HTML Document 5 // response.setContentType("application/csv;charset=UTF-8"); // 显示文件类型 Microsoft Excel 逗号分隔值文件 6 7 request.setCharacterEncoding("UTF-8"); 8 response.addHeader("Content-disposition", "attachment; filename="+ new String(file.getName().getBytes(), "ISO8859-1")); // 解决文件名乱码问题,及文件名中的中文被自动去除问题 9 response.addHeader("Content-Length", String.valueOf(file.length())); 10 11 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); 12 BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); 13 14 byte[] buff = new byte[4096]; 15 int bytesRead; 16 while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { 17 bos.write(buff, 0, bytesRead); 18 } 19 20 bis.close(); 21 bos.close(); 22 }