@GetMapping("/download_excel_template") publicvoiddownloadFile(HttpServletResponse response)throws IOException { InputStream inputStream = null; OutputStream out = null; try { Resource resource = new ClassPathResource("file/七星区人事信息模板.xlsx"); File file = resource.getFile(); String filename = resource.getFilename(); inputStream = new FileInputStream(file); //强制下载不打开 response.setContentType("application/octet-stream"); out = response.getOutputStream(); //使用URLEncoder来防止文件名乱码或者读取错误 response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename, "UTF-8")); //当不写上一行代码时, 浏览器读到有后缀的文件时会尝试打开;即使下载也会命名为file。 //加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃” response.addHeader("Content-Length", String.valueOf(file.length())); int b = 0; byte[] buffer = newbyte[1000000]; while (b != -1) { b = inputStream.read(buffer); if(b!=-1) out.write(buffer, 0, b); } LOG.info("下载模板Excel成功"); // return new Response(200, "下载成功"); } catch (IOException e) { e.printStackTrace(); // return new Response("下载失败, 请重新下载"); } finally { inputStream.close(); out.close(); out.flush(); } } }
如果下载方法有返回值的话, 会报错
rg.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.lang.Boolean] with preset Content-Type 'application/octet-stream;charset=UTF-8'
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed