/** * 文件下载 * * @param response * @param file */ public static void downLoad(HttpServletResponse response, File file) { if (file.exists()) { response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); byte[] buffer = new byte[1024]; try (OutputStream os = response.getOutputStream(); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis);) { response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8")); int i = bis.read(buffer); while (i != -1) { os.write(buffer,0,i); i = bis.read(buffer); } } catch (IOException e) { e.printStackTrace(); } } }
避免的文件下载被破坏的关键代码: