下载文件java spring rest api

时间:2017-03-13 15:13:09

标签: java excel spring rest io

我想制作一个休息api控制器(弹簧启动),当用get获取请允许我下载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,但现在我想让下载的文件有一些特定的名称,如:assessName.xls或userDateEndDate.xls或其他一些东西,有没有办法编辑响应实体这样做?所以我不必将映射命名为“download.xls”

1 个答案:

答案 0 :(得分:5)

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

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

ResponseEntity 我假设您可以使用以下内容:

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