SpringBoot java 通过文件流下载文件, 页面乱码 | 您所在的位置:网站首页 › springboot导出txt文件 › SpringBoot java 通过文件流下载文件, 页面乱码 |
SpringBoot 通过文件流下载文件
1. 发成错误情况的结果及代码
1. 发成错误情况的结果及代码
分析之后,我感觉是这句:response.getOutputStream() 和 // 清空response response.reset(); // 设置response的Header response.setCharacterEncoding("UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 告知浏览器文件的大小 response.addHeader("Content-Length", String.valueOf(file.length())); response.setContentType("application/octet-stream");之间的先后位置有误,response的header和contentType应该在response.getOutputStream()传递给new BufferedOutputStream 这个缓冲输出流对象之前指定好参数。修改后的正确代码如下。 @GetMapping(value = "downLoadQualification") public void downLoadQualification(@RequestParam Integer id, HttpServletResponse response) throws UnsupportedEncodingException { SysFile sysFile = this.sysFileService.getSysFile(SnyqConstants.CHECK_RECORD_FILE_CATEGORY, id); String filePath = sysFile.getFilePath(); File file = new File(filePath); String fileName = file.getName(); int i = fileName.lastIndexOf('.'); String extension = fileName.substring(i + 1); // 清空response response.reset(); // 设置response的Header response.setCharacterEncoding("UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 告知浏览器文件的大小 response.addHeader("Content-Length", String.valueOf(file.length())); response.setContentType("application/octet-stream"); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { FileInputStream fi = new FileInputStream(file); bis = new BufferedInputStream(fi); int len = 0; byte[] buffer = new byte[4 * 1024]; bos = new BufferedOutputStream(response.getOutputStream()); while ((len = bis.read(buffer, 0, buffer.length)) != -1) { bos.write(buffer, 0, len); } bos.flush(); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bis.close(); } } catch (IOException e) { throw new CustomException(e.getMessage()); } } }之后问题解决 |
CopyRight 2018-2019 实验室设备网 版权所有 |