Downloading a file from spring controllers

前端 未结 14 906
渐次进展
渐次进展 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:47

    This can be a useful answer.

    Is it ok to export data as pdf format in frontend?

    Extending to this, adding content-disposition as an attachment(default) will download the file. If you want to view it, you need to set it to inline.

    0 讨论(0)
  • 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:

    <a th:href="@{|/dbreport/files/${file_name}|}">Download</a>
    

    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.

    0 讨论(0)
提交回复
热议问题