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
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.
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.