下载文件java spring Rest api

问题描述 投票:0回答:1

我想制作一个 REST API 控制器(Spring Boot),当使用 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 doesn't 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(作为映射)文件时,一切似乎都工作得很好,但现在我想让下载的文件具有一些特定的名称,例如:evaluatedName.xls 或 userDateEndDate.xls 或其他一些东西,有没有办法编辑响应实体来做到这一点?这样我就不必将映射命名为“download.xls”

java excel spring rest io
1个回答
6
投票

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

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

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

 ResponseEntity.ok().header("Content-Disposition","attachment; filename=" + csvName );
© www.soinside.com 2019 - 2024. All rights reserved.