在项目中经常会用到文件下载的功能,比如下载excel模板,这里简单记录一下实现过程
将模板文件放到项目资源文件目录中,也可以自定义其他位置,只要通过路径能找到该文件就行:
2、controller层写下载的接口
@GetMapping("downloadExcel") public void downloadExcel(HttpServletResponse httpServletResponse) { InputStream inputStream = null; try (ServletOutputStream outputStream = httpServletResponse.getOutputStream()) { //设置响应头信息,包括下载后的文件名和编码等 httpServletResponse.addHeader("content-disposition", String.format("attachment;filename= %s", URLEncoder.encode("导入模板.xlsx", "utf-8"))); httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); httpServletResponse.setCharacterEncoding("UTF-8"); //在文件夹里获取到文件并转为流 inputStream = new ClassPathResource("/senseXlsx.xlsx").getInputStream(); byte[] b = streamToByteArray(inputStream); httpServletResponse.getOutputStream().write(b); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
前端直接调用这个接口就可以实现下载啦
来源地址:https://blog.csdn.net/qq_44761860/article/details/130384841