springboot中Excel文件下载踩坑大全

目录

  • 项目场景:Spring boot文件下载
  • 问题一:下载的文件名称出现中文乱码的问题
  • 问题二:在swagger中测试下载接口,点击下载的文件,发现文件名是乱码的问题
  • 问题四:开发环境下载成功,打成jar包发布到服务器上部署就出现下载失败问题
  • 完整代码

项目场景:Spring boot文件下载 调用接口下载spring boot工程的resources目录下的excel模板文件,非常常见的一个文件下载功能,但是却容易遇到很多坑,下面总结记录下。

问题一:下载的文件名称出现中文乱码的问题 解决方案:
response.setHeader("Content-Disposition","attachment; filename=" + new String("下载模板".getBytes("UTF-8"), "ISO8859-1"));

说明:
这是网上最常见的解决方案,经过这样的修改后,在浏览器上调用get请求下载的文件确实没有出现文件名中文乱码了。
但是在swagger里面测试接口,下载的问题还是会出现中文乱码。

问题二:在swagger中测试下载接口,点击下载的文件,发现文件名是乱码的问题 这里我项目中使用的是springdoc-openapi-ui 1.5.9,基于的是openapi3.0的协议。
整体使用方式和界面和swagger类似。
swagger中下载的文件,点击开发后,文件名乱码问题:

springboot中Excel文件下载踩坑大全
文章图片

解决方案:
response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode("线索导入模板.xlsx","utf8"));

说明:
通过URLEncoder.encode函数对文件名称处理后,无论是在浏览器调用GET请求下载文件,还是Swagger中调用下载接口,都不会出现文件名乱码问题。
问题三:下载的excel文件打开时总是提示部分内容有问题,尝试恢复。
springboot中Excel文件下载踩坑大全
文章图片


springboot中Excel文件下载踩坑大全
文章图片

解决办法:
给response的Header设置大小:
/加上设置大小 下载下来的excel文件才不会在打开前提示修复response.addHeader("Content-Length",String.valueOf(file.length()));


问题四:开发环境下载成功,打成jar包发布到服务器上部署就出现下载失败问题 原因:
Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。
解决:
通过ClassPathResource读取文件流
ClassPathResource classPathResource = new ClassPathResource("template/template.xlsx");


完整代码 1、控制层代码
@Operation(summary = "下载模版",description = "下载模版")@GetMapping("/download")public void download(HttpServletResponse response){templateService.download(response); }

2、下载方法实现
/** * 下载线索模板 * @param response */public void download(HttpServletResponse response) {InputStream inputStream = null; BufferedInputStream bis = null; OutputStream outputStream = null; try {ClassPathResource classPathResource = new ClassPathResource("template/template.xlsx"); inputStream = classPathResource.getInputStream(); response.setContentType("application/octet-stream"); response.setHeader("content-type", "application/octet-stream"); //待下载文件名String fileName = URLEncoder.encode("模板.xlsx","utf8"); response.setHeader("Content-Disposition", "attachment; fileName=" + fileName); //加上设置大小 下载下来的excel文件才不会在打开前提示修复response.addHeader("Content-Length",String.valueOf(classPathResource.getFile().length())); byte[] buff = new byte[1024]; outputStream = response.getOutputStream(); bis = new BufferedInputStream(inputStream); int read = bis.read(buff); while (read != -1) {outputStream.write(buff, 0, buff.length); outputStream.flush(); read = bis.read(buff); }} catch ( IOException e ) {log.error("文件下载失败,e"); } finally {IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(bis); }}

参考:https://blog.csdn.net/Hi_Boy_/article/details/107198371
【springboot中Excel文件下载踩坑大全】到此这篇关于springboot中Excel文件下载踩坑大全的文章就介绍到这了,更多相关springboot Excel文件下载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读