SpringMVC实现文件下载功能(文件导出功能)

梦里梦外; 2022-05-09 03:48 462阅读 0赞

1.页面代码

  1. <a class="layui-btn" href="${pageContext.request.contextPath}/bAndWListManage/downloadWhiteListTmp.do" onclick="downloadTemplate();">模板下载</a>

2.后台代码

  1. @RequestMapping("downloadWhiteListTmp")
  2. public ResponseEntity<byte[]> downloadWhiteListTmp(HttpServletRequest request) {
  3. HttpHeaders headers = new HttpHeaders();
  4. String fileName="importVehicleWhitelist.xls";
  5. ServletContext servletContext = request.getServletContext();
  6. String realPath = servletContext.getRealPath("/bwlmm/templateFiles/"+fileName);
  7. File file = new File(realPath);
  8. InputStream in;
  9. byte[] body=null;
  10. ResponseEntity<byte[]> response =null;
  11. try {
  12. in = new FileInputStream(new File(realPath));
  13. body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
  14. in.read(body);//读入到输入流里面
  15. fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
  16. headers.add("Content-Disposition", "attachment;filename="+fileName);
  17. HttpStatus statusCode = HttpStatus.OK;//设置响应吗
  18. response =new ResponseEntity<byte[]>(body, headers, statusCode);
  19. } catch (FileNotFoundException e) {
  20. e.printStackTrace();
  21. }//将该文件加入到输入流之中
  22. catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. return response;
  26. }

3.说明

我的文件路径

70

发表评论

表情:
评论列表 (有 0 条评论,462人围观)

还没有评论,来说两句吧...

相关阅读

    相关 django 实现文件下载功能

    第一种方法 第一种方法,直接把链接地址指向要下载的静态文件,在页面中点击该链接,可以直接打开该文件,在链接上点击右键,选择“另存为”可以保存该文件到本地硬盘。但是我成功