在SpringBoot2.1中尝试下载不带扩展名的文件时获得404
当我尝试下载一些没有扩展名的文件时,我得到在SpringBoot2.1中尝试下载不带扩展名的文件时获得404,spring,spring-boot,downloadfile,Spring,Spring Boot,Downloadfile,当我尝试下载一些没有扩展名的文件时,我得到[http-bio-8443-exec-8]WARN o.s.w.s.PageNotFound-在DispatcherServlet中找不到URI为[server/directory/README-325]的http请求的映射,名称为“download rest”。 此README-325文件是一个没有扩展名的文件。当我们尝试下载带有扩展名的文件时,一切都正常,但正如我所说的,问题是那些没有扩展名的文件。当我们在这个文件README-325上添加扩展名时
[http-bio-8443-exec-8]WARN o.s.w.s.PageNotFound-在DispatcherServlet中找不到URI为[server/directory/README-325]的http请求的映射,名称为“download rest”
。
此README-325文件是一个没有扩展名的文件。当我们尝试下载带有扩展名的文件时,一切都正常,但正如我所说的,问题是那些没有扩展名的文件。当我们在这个文件README-325上添加扩展名时,这个控制器被调用
@RequestMapping(value = "/download")
@ResponseBody
public void fileDownload(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true, value = "server") String server, @RequestParam(required = true, value = "directory") String directory, @RequestParam(required = true, value = "fileName") String fileName) throws IOException {}
但当文件没有扩展名时,则不会调用任何控制器。有人知道为什么吗?
注:类似问题的解决方案对我们没有帮助。Spring的版本是3.2.3.Release,Spring的启动版本是2.1。Spring的dispatchservlet(负责将请求路由到控制器的类)在url的最后部分包含扩展名(点+字母)与没有扩展名时的行为不同。实际上,如果没有扩展名,Spring肯定不会试图获取文件 下面是我用来配置Spring的一个类,用于停止将带有扩展名的URL作为特殊内容进行威胁(因为我的路径可能包含电子邮件地址)。这不是您想要的——因为您确实喜欢Spring自动为您获取文件的能力——但它突出显示了Spring如何尝试以不同的方式解析扩展
@Configuration
public class SpringWebConfig implements WebMvcConfigurer
{
//Allows url to end with a suffix (e.g.: /users/user1@gmail.com). Without this configuration,
//the ".com" suffix would be automatically removed from the path variable.
@Override
public void configurePathMatch(PathMatchConfigurer matcher)
{
matcher.setUseSuffixPatternMatch(false);
}
//Allows url to end with the ".com" suffix with Spring NOT throwing a "http media type" error.
//See: https://blog.georgovassilis.com/2015/10/29/spring-mvc-rest-controller-says-406-when-emails-are-part-url-path/
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer)
{
//Don't look at the url for determining the response media type
contentNegotiationConfigurer.favorPathExtension(false);
//If the request header says it wants a response type, try to give it.
contentNegotiationConfigurer.ignoreAcceptHeader(false);
//Otherwise, return json.
contentNegotiationConfigurer.defaultContentType(MediaType.APPLICATION_JSON);
}
}
查看错误消息,文件名似乎是作为请求路径的一部分传递的: 找不到URI为[download_path/README-325]的HTTP请求的映射 但从控制器的定义来看,它应该作为请求参数传递,如:
/download?server=some-server&directory=some-directory&filename=README-325
因此,您要么需要适应调用服务的方式,要么需要适应控制器的实现
编辑:
@RequestParam
在URL末尾的“?”后面传递,并用“&”分隔。但是你在路径中发送这些值,在你的控制器中,你需要@PathVariable
。谢谢你的回答,我编辑了我的问题(我写了确切的路径),因为可能你误解了我:)“Spring版本是3.2.3.Release,Spring启动版本是2.1”-这是不太可能的。如果您的Spring引导版本是2.1,那么您的Spring核心版本在5.x范围内。