废话不多说,直接上代码,注释写得也比较清楚。
/** * 下载模板文件 * @param filename 要下载的文件在工程中的路径,如/template/userTemplate.xls */ @RequestMapping("/common/downloadtemplatefile") public void downloadTemplateFile(String filename, HttpServletResponse response, HttpServletRequest request) { LOGGER.info("【下载模板文件】filename : " + filename); if (StringUtils.isNotBlank(filename)) { LOGGER.warn("【模板文件路径为空】"); throw new RuntimeException("模板文件路径为空"); } // 截取后缀名 int lastIndexOfPoint = filename.lastIndexOf("."); String suffix = filename.substring(lastIndexOfPoint); // 需要下载的文件 String filepath = request.getSession().getServletContext().getRealPath(filename); File myfile = new File(filepath); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + filename.getBytes() + suffix); response.addHeader("Content-Length", "" + myfile.length()); response.setContentType("application/octet-stream"); OutputStream toClient = null; InputStream fis = null; //打开文件输入流 和 servlet输出流 try { toClient = new BufferedOutputStream(response.getOutputStream()); fis = new BufferedInputStream(new FileInputStream(myfile)); //通过ioutil 对接输入输出流,实现文件下载 IOUtils.copy(fis, toClient); toClient.flush(); } catch (Exception e) { LOGGER.error("【文件下载失败】", e); throw new RuntimeException("文件下载失败"); } finally { //关闭流 IOUtils.closeQuietly(fis); IOUtils.closeQuietly(toClient); } }
时间: 2024-10-09 18:38:55