How to redirect page to static file in Spring Boot?
如何在Spring Boot(MVC)中重定向页面Web请求/请求映射以指向静态文件(例如:.txt,.json,.jpg,.mp4等)。 我在Spring Boot项目中所拥有的只是一个application.properties文件和@Controllers。
我希望用户在向浏览器中的网址发出网络请求以要求下载文件时(不要像.html,.jsp那样使用它来尝试呈现页面)
您可以在Spring中使用" redirect:"前缀进行重定向。 从Spring文档中:
A logical view name such as redirect:/myapp/some/resource will redirect relative to the current Servlet context, while a name such as redirect:http://myhost.com/some/arbitrary/path will redirect to an absolute URL.
一个例子是:
1 2 3 4 |
您可以在以下任何位置的类路径中直接放置要直接提供的静态资源(请参阅提供静态资源):
1 2 3 | private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/","classpath:/public/" }; |
您可以通过告诉响应您希望附加可下载文件来实现。 然后,您可以简单地编写要下载的内容。
这是一个例子:
1 2 3 4 5 6 7 8 9 10 11 | @ResponseStatus(HttpStatus.OK) @RequestMapping(value ="/myredirect", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public void downloadFile(HttpServletResponse response) { // Remove this instruction if you wish to disable the download dialog. response.setHeader("Content-Disposition","attachment; filename=filename.ext"); // Load your file content as byte. byte[] fileContent = IOUtils.toByteArray(new ClasspathResource("myfile").getIntputStream()); response.getOutputStream().write(fileContent); } |
另一方面,如果您只想直接映射到静态文件。 您可以使用Spring Boot Starter Web的默认
默认情况下,在