下载文件java spring rest api

我想做一个rest的API控制器(春季启动),当获得请愿将允许我下载一个Excel文件。 目前我有这个端点:

@RequestMapping(value = "/download.xls", method = RequestMethod.GET) public ResponseEntity Survey_Reports(@RequestParam(value = "evaluated") String evaluated){ return surveyService.getSurveysFile(evaluated); } 

最终会调用这个方法:

 public static ResponseEntity getDownloadResponse() { File file2Upload = new File("Survey_Reports.xls"); Path path = Paths.get(file2Upload.getAbsolutePath()); ByteArrayResource resource = null; try { resource = new ByteArrayResource(Files.readAllBytes(path)); } catch (IOException e) { logger.error("there was an error getting the file bytes ", e); } return ResponseEntity.ok() .contentLength(file2Upload.length()) //this line doesnt seem to work as i set the file format in the controller request mapping .contentType(MediaType.parseMediaType("application/vnd.ms-excel")) .body(resource); } 

一切似乎工作半罚款,因为我得到download.xls(作为映射)文件correclty,但现在我想使下载的文件有一些特定的名称,如:evaluateName.xls或userDateEndDate.xls或一些其他的东西,是有一种方法可以编辑响应实体吗? 所以我不必命名映射“download.xls”

HttpServletResponse响应的上下文中,你可以这样做

 response.setContentType("application/csv"); response.setHeader("Content-Disposition", "attachment; filename=" + csvName); 

ResponseEntity我假设你可以使用这样的事情:

  ResponseEntity.ok().header("Content-Disposition","attachment; filename=" + csvName );