繁体   English   中英

下载文件java spring rest api

[英]download file java spring rest api

我想制作一个休息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,但现在我想让下载的文件有一些特定的名称,如:evaluateName.xls或userDateEndDate.xls或其他一些东西,是有没有办法编辑响应实体呢? 这样我就不必将映射命名为“download.xls”

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM