Downloading a file from spring controllers

前端 未结 14 1076
渐次进展
渐次进展 2020-11-22 01:06

I have a requirement where I need to download a PDF from the website. The PDF needs to be generated within the code, which I thought would be a combination of freemarker and

14条回答
  •  一整个雨季
    2020-11-22 01:48

    In my case I'm generating some file on demand, so also url has to be generated.

    For me works something like that:

    @RequestMapping(value = "/files/{filename:.+}", method = RequestMethod.GET, produces = "text/csv")
    @ResponseBody
    public FileSystemResource getFile(@PathVariable String filename) {
        String path = dataProvider.getFullPath(filename);
        return new FileSystemResource(new File(path));
    }
    

    Very important is mime type in produces and also that, that name of the file is a part of the link so you has to use @PathVariable.

    HTML code looks like that:

    Download
    

    Where ${file_name} is generated by Thymeleaf in controller and is i.e.: result_20200225.csv, so that whole url behing link is: example.com/aplication/dbreport/files/result_20200225.csv.

    After clicking on link browser asks me what to do with file - save or open.

提交回复
热议问题