Springboot下載功能,附件超過8K不能顯示下載彈窗,頁面亂碼問題
阿新 • • 發佈:2018-10-13
strong oid map str 亂碼 ica req 大小 出現
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不能顯示下載彈窗,頁面亂碼問題