下载文件 java spring rest api

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42767079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:51:39  来源:igfitidea点击:

download file java spring rest api

javaexcelspringrestio

提问by Fernando Castilla Ospina

i want to make a rest api controller (spring boot) that when petitioned with a get will allow me to download an excel file. currently i have this endpoint:

我想制作一个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);

}

wich ultimately calls to this method:

最终调用此方法:

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);
}

everything seems to work semi-fine as i get the download.xls(as the mapping) file correclty, but now i want to make the downloaded file have some specific name like: evaluatedName.xls or userDateEndDate.xls or some other stuff, is there a way to edit the response entity to do so? so that i dont have to name the mapping "download.xls"

当我得到 download.xls(作为映射)文件正确性时,一切似乎都正常工作,但现在我想让下载的文件具有一些特定的名称,例如:evaluateName.xls 或 userDateEndDate.xls 或其他一些东西,是有没有办法编辑响应实体来这样做?这样我就不必将映射命名为“download.xls”

回答by Matej Marconak

In context of HttpServletResponse responseyou can do this like this

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

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

and for ResponseEntityi assume you can use something like this:

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

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