赞
踩
前段时间做项目时,有个需要下载excel模板的需求,但是由于用的是K8S部署,不能直接把模板文件放到指定的服务器,于是就把模板文件放到了项目resources目录下,然后本地测试一切正常,顺利提到了测试。
结果测试环境除了问题,下载下来是个空的excel,返回的response数据也是空。于是开始找问题,本地postman测试,response返回是乱码(其实文件是正常的,应该该是编码问题),文件下载出来没问题。postman连接测试接口,response是空,下载的文件还是空excel。然后网上各种找解决方案,发现百度出来的帖子,基本上千篇一律,就是一个帖子被N多人CV的,连格式都一模一样,找小伙伴帮忙看,也没有找到解决方案,问题就这么搁置了两天,一直没解决。
后来偶尔看到一个帖子,用了不一样的方法读取,我就试了一下,问题就解决了。直接贴代码,注意resource别导错包。
- import org.springframework.core.io.Resource;
-
- /**
- * 模板下载
- */
- public void downloadTemplate(HttpServletResponse response){
- OutputStream out = null;
- InputStream in = null;
- ByteArrayOutputStream bos = null;
- String fileName = "导入模版";
-
- try {
- // 读取模板
- Resource res = new ClassPathResource("Template.xlsx");
- XSSFWorkbook workbook = new XSSFWorkbook(res.getInputStream());
-
- // 转换为字节流
- bos = new ByteArrayOutputStream();
- workbook.write(bos);
- byte[] barray = bos.toByteArray();
- in = new ByteArrayInputStream(barray);
-
- response.reset();
- response.setContentType("application/octet-stream");
- response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
- out = response.getOutputStream();
- byte[] b = new byte[1024];
- int len;
- while ((len = in.read(b)) > 0) {
- out.write(b, 0, len);
- }
- out.flush();
- } catch (Exception e) {
- log.error("下载模板失败",e);
- } finally {
- if (null != in) {
- try {
- in.close();
- } catch (IOException e) {
- log.error("关闭资源异常",e);
- }
- in = null;
- }
- if (null != out) {
- try {
- out.close();
- } catch (IOException e) {
- log.error("关闭资源异常",e);
- }
- out = null;
- }
- if (null != bos) {
- try {
- bos.flush();
- bos.close();
- } catch (IOException e) {
- log.error("关闭资源异常",e);
- }
- out = null;
- }
- }
- }

困扰我两天的问题,Resource res = new ClassPathResource("whiteListTemplate.xlsx"); 这一行代码就解决了。
总结:本地测试时,可以直接读取到项目中的文件,所以能把文件下载下来。但是线上部署用的Docker和K8S,是jar包运行的,在读取文件的时候,因为之前的方法问题,一直读取不到文件内容,然后用Resource res = new ClassPathResource("Template.xlsx"); 是通过流的形式读取的,resource继承了InputStreamSource,所以才能以流的方式读取到文件内容。
因为对K8S、Docker和Spring源码并不了解,以上只是我个人的猜想,希望知道原理或者正确答案的小伙伴不吝赐教,万分感谢!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。