【问题标题】:download file java spring rest api下载文件 java spring rest api
【发布时间】:2017-08-03 16:08:31
【问题描述】:

我想制作一个 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 doesnt seem to work as i set the file format in the controller request mapping
            .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
            .body(resource);
}

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

【问题讨论】:

    标签: java excel spring rest io


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 这行得通:D,这解决了映射中对 .xls 的需求,让我修改名称以方便我,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2019-01-08
    相关资源
    最近更新 更多