下载文件java spring rest api

Fer*_*ina 4 java io rest excel spring

我想制作一个休息api控制器(弹簧启动),当用get获取请允许我下载excel文件.目前我有这个端点:

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

    return surveyService.getSurveysFile(evaluated);

}
Run Code Online (Sandbox Code Playgroud)

最终要求这种方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

一切似乎工作半精细,因为我得到download.xls(作为映射)文件correclty,但现在我想让下载的文件有一些特定的名称,如:evaluateName.xls或userDateEndDate.xls或其他一些东西,是有没有办法编辑响应实体呢?这样我就不必将映射命名为"download.xls"

小智 5

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

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

对于ResponseEntity,我假设你可以使用这样的东西:

 ResponseEntity.ok().header("Content-Disposition","attachment; filename=" + csvName );
Run Code Online (Sandbox Code Playgroud)