2017-03-13 121 views
1

我想做一個休息api控制器(彈簧啓動),當獲得get請求時將允許我下載一個excel文件。目前,我有這個端點:下載文件java spring rest api

@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」

回答

3

在上下文HttpServletResponse的響應你可以做到這一點像這樣

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

ResponseEntity我想你可以使用像這:

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

這工作:D,這固定需要.xls在映射中,讓我修改名稱爲我的方便,非常感謝你 –