gpt4 book ai didi

java - 使用 Spring Boot 和 Thymeleaf 创建文件下载链接

转载 作者:搜寻专家 更新时间:2023-11-01 01:33:29 25 4
gpt4 key购买 nike

这听起来像是一个微不足道的问题,但经过几个小时的搜索,我还没有找到答案。据我所知,问题是我试图从 Controller 返回一个 FileSystemResource 并且 Thymeleaf 希望我提供一个 String 资源,它将使用它来渲染下一页。但是由于我要返回一个 FileSystemResource,所以出现以下错误:

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

我使用的 Controller 映射是:

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

我的 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>

然后您还需要更改 Controller 并包含 @ResponseBody 注释:

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

关于java - 使用 Spring Boot 和 Thymeleaf 创建文件下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com