1 public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception { 2 File f = new File(filePath); 3 if (!f.exists()) { 4 response.sendError(404, "File not found!"); 5 return; 6 } 7 BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); 8 byte[] buf = new byte[1024]; 9 int len = 0; 10 11 response.reset(); // 非常重要 12 if (isOnLine) { // 在线打开方式 13 URL u = new URL("file:///" + filePath); 14 response.setContentType(u.openConnection().getContentType()); 15 response.setHeader("Content-Disposition", "inline; filename=" + f.getName()); 16 // 文件名应该编码成UTF-8 17 } else { // 纯下载方式 18 response.setContentType("application/x-msdownload"); 19 response.setHeader("Content-Disposition", "attachment; filename=" + f.getName()); 20 } 21 OutputStream out = response.getOutputStream(); 22 while ((len = br.read(buf)) > 0) 23 out.write(buf, 0, len); 24 br.close(); 25 out.close(); 26 }标签:文件,filePath,代码,len,br,new,response,下载,out From: https://www.cnblogs.com/jinfangwei/p/17680893.html