Search code examples
javadownloadspring-bootthymeleaf

Creating a file download link using Spring Boot and Thymeleaf


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.


Solution

  • 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()));
    }