spring boot 实现文件下载
1 | html 代码 js部分<br> window.location.href= this .Baseurl+ '/plan/down?file=' +filename; |
spring boot 后台代码
@GetMapping("/down") public HttpServletResponse down(HttpServletResponse response, HttpServletRequest request,@RequestParam("file") String files ) { String fileName = files;// 设置文件名,根据业务需要替换成要下载的文件名 if (fileName != null) { //设置文件路径 String pahre=System.getProperty("user.dir")+ "\\report\\"; File file = new File(pahre , fileName); if (file.exists()) { response.setContentType("application/force-download");// 设置强制下载不打开 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; }
文件的默认位置在当前运行目录的report文件下
个人公众号
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步