当前位置: 首页 > 后端技术 > Java

springboot文件下载功能开发!

时间:2023-04-02 00:01:55 Java

1L极天最近挤进了一个需要基于docker集群部署的环境,在各个服务器节点上下载日志文件(对应的服务文件路径已经映射)。收集日志的思路是在每个机器节点上安装一个monitor.jar监控服务,通过当前主程序调用monitor并返回相应的数据。主要程序代码如下try{Stringurl=String.format("http://%s:%d/api/filelist/files/%s",remoteIp,8887,appName);Stringres=HttpUtil.get(url,1000);ja=JSONArray.parseObject(res,List.class);}catch(Exceptione){ja=Collections.emptyList();log.error(e.getMessage());}返回Resp.OK(ja);}@GetMapping("loadLOgQue")publicResploadLOgQue(@RequestParam("remoteIp")StringremoteIp,@RequestParam("appName")StringappName,@RequestParam("fileName")StringfileName,HttpServletResponsehttpServletResponse){try{Stringurl=String.format("http://%s:%d/api/filelist/files/%s/%s",remoteIp,8887,文件名,应用名);httpServletResponse.setContentType("application/x-download");httpServletResponse.setHeader("content-Disposition","attachment;filename="+fileName);ServletOutputStreamoutputStream=httpServletResponse.getOutputStream();HttpUtil.download(url,outputStream,true);}catch(Exceptione){log.error(e.getMessage());}returnResp.OK("成功");}}monitor服务代码如下:@RestController@RequestMapping("api/filelist")publicclassFileListController{@AutowiredFileStorageServicefileStorageService;@GetMapping("/files/{appName}")publicResponseEntity>files(@PathVariable("appName")StringappName){Listfiles=fileStorageService.loadListsByAppName(appName).map(path->{StringfileName=path.getFileName().toString();Stringurl=MvcUriComponentsBuilder.fromMethodName(FileListController.class,"getFile",path.getFileName().toString(),appName).build().toString();returnnewUploadFile(fileName,url);}).collect(Collectors.toList());返回ResponseEntity.ok(文件);}@GetMapping("/files/{filename:.+}/{appName}")publicResponseEntitygetFile(@PathVariable("filename")Stringfilename,@PathVariable("appName")StringappName){资源文件=fileStorageService.load(文件名,应用程序姓名);返回ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+file.getFilename()+"\"").body(file);}}参考如下基于springBoot2.0的RestFul风格文件下载