使用Spring Boot和Thymeleaf创建文件下载链接 [英] Creating a file download link using Spring Boot and Thymeleaf
问题描述
这听起来像是一个琐碎的问题,但是经过数小时的搜索,我还没有找到答案。据我了解,问题是我试图从控制器返回 FileSystemResource
,Thymeleaf希望我提供一个 String
资源,它将使用该资源呈现下一页。但是由于返回的是 FileSystemResource
,因此出现以下错误:
org.thymeleaf.exceptions.TemplateInputException:解决模板产品/下载时出错,模板可能不存在或任何配置的模板解析器
$ p $无法访问p>
我使用的控制器映射是:
@RequestMapping(value = / products / download,method = RequestMethod.GET)
public FileSystemResource downloadFile(@Param(value = id)Long id){
产品product = productRepo.findOne(id);
返回新的FileSystemResource(new File(product.getFileUrl()));
}
我的HTML链接如下所示:
< a th:href = $ {'products / download?id ='+ product.id}>< span th:text = $ {product.name}< / span>< / a>
我不想重定向到任何地方,我只需要在单击链接后下载文件。这实际上是正确的实施方式吗?我不确定。
解决方案您需要更改
th:href
看起来像这样:< a th:href = @ {| / products / download?id = $ { product.id} |}>< span th:text = $ {product.name}>< / span>< / a>
然后,您还需要更改控制器并包含
@ResponseBody
批注:@RequestMapping(value = / products / download,method = RequestMethod.GET)
@ResponseBody
public FileSystemResource downloadFile(@Param(value = id)Long id){
产品product = productRepo.findOne(id);
返回新的FileSystemResource(new File(product.getFileUrl()));
}
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 aString
resource using which it will render the next page. But since I am returning aFileSystemResource
, 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())); }
这篇关于使用Spring Boot和Thymeleaf创建文件下载链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!