This might sound like a trivial question, but after hours of searching I am yet to find an answer to this. The problem, as far as I understand, is that I am trying to return a FileSystemResource
from the controller and Thymeleaf expects me to supply a String
resource using which it will render the next page. But since I am returning a FileSystemResource
, I get the following error:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "products/download", template might not exist or might not be accessible by any of the configured Template Resolvers
The controller mapping I have used is:
@RequestMapping(value="/products/download", method=RequestMethod.GET)
public FileSystemResource downloadFile(@Param(value="id") Long id) {
Product product = productRepo.findOne(id);
return new FileSystemResource(new File(product.getFileUrl()));
}
My HTML link looks something like this:
<a th:href="${'products/download?id=' + product.id}"><span th:text="${product.name}"></span></a>
I don't want to be redirected anywhere, I just need the file downloaded once the link is clicked. Is this actually the right implementation? I'm not sure.
You need to change the th:href
to look like:
<a th:href="@{|/products/download?id=${product.id}|}"><span th:text="${product.name}"></span></a>
Then also you need to change your controller and include the @ResponseBody
annotation:
@RequestMapping(value="/products/download", method=RequestMethod.GET)
@ResponseBody
public FileSystemResource downloadFile(@Param(value="id") Long id) {
Product product = productRepo.findOne(id);
return new FileSystemResource(new File(product.getFileUrl()));
}
Have a href url like
<a th:href="@{|/download?id=${obj.id}|}">download</a>
Then In controller define like below to write the file to the response object.
@RequestMapping(value="/download", method=RequestMethod.GET)
public void downloadFile(@Param(value="id") Long id,HttpServletResponse response) {
try {
Ticket ticket = this.findById(id);
String fileName = Paths.get(property.getFileLocation()).resolve(ticket.getFilePath()).toString();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
FileInputStream inputStream;
try {
inputStream = new FileInputStream(fileName);
try {
int c;
while ((c = inputStream.read()) != -1) {
response.getWriter().write(c);
}
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
response.getWriter().close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With