标签:pat attach output 一个 超过 color http eth res
Springboot项目中遇到一个文件下载问题,当文件大小超过8K时,不会出现弹出窗,而是直接在页面显示乱码。
有问题的源码如下:
@RequestMapping(value = "/exportFile") public void exportFile(HttpServletRequest request, HttpServletResponse response, String fileName) { String filePath = ReflectUtil.class.getClassLoader().getResource("").getPath(); File exportfile = new File(filePath + "/export/" + fileName); try (FileInputStream is = new FileInputStream(exportfile ); OutputStream out = response.getOutputStream();) { if (is != null) { int b = 0; byte[] buffer = new byte[4096]; while (b != -1) { b = is.read(buffer); if (b != -1) { out.write(buffer, 0, b); } } response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + "exportFile.xls"); response.flushBuffer(); out.flush(); } } catch (IOException e) { log.error("error is {}", e); } }
解决方案:将上面蓝色标识的二行放到方法最上面,问题解决。
@RequestMapping(value = "/exportFile") public void exportFile(HttpServletRequest request, HttpServletResponse response, String fileName) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + "exportFile.xls"); String filePath = ReflectUtil.class.getClassLoader().getResource("").getPath(); File exportfile = new File(filePath + "/export/" + fileName); try (FileInputStream is = new FileInputStream(exportfile ); OutputStream out = response.getOutputStream();) { if (is != null) { int b = 0; byte[] buffer = new byte[4096]; while (b != -1) { b = is.read(buffer); if (b != -1) { out.write(buffer, 0, b); } } response.flushBuffer(); out.flush(); } } catch (IOException e) { log.error("error is {}", e); } }
Springboot下载功能,附件超过8K不能显示下载弹窗,页面乱码问题
标签:pat attach output 一个 超过 color http eth res
原文地址:https://www.cnblogs.com/wanbao/p/9783241.html