【发布时间】:2017-06-28 20:05:28
【问题描述】:
我正在使用Spring boot v1.5.3.RELEASE,现在,如果我不包含扩展文件,我可以正常下载文件。当我尝试使用典型的文件扩展名(jpg、jpeg、mp3、mp4 等)下载文件时,Spring 会放弃该请求。一个示例请求可能是:localhost:8888/public/file/4.jpg
我的 Application.java 是:
public class Application extends RepositoryRestMvcConfiguration {
public static void main(String[] args) {
// System.getProperties().put( "server.port", 8888 );
// System.getProperties().put( "spring.thymeleaf.mode", "LEGACYHTML5" );
SpringApplication.run(Application.class, args);
}
@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {
return new RepositoryRestConfigurerAdapter() {
@Override
public void configureRepositoryRestConfiguration(
RepositoryRestConfiguration config) {
config.exposeIdsFor(Noticia.class, file.class, Label.class, Reaction.class);
}
};
}
}
我的 Controller.java 代码是:
@RequestMapping(value = "public/file/{filename}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public FileSystemResource getPublicFileWithSuffix(@PathVariable("filename") String filename) {
System.out.println("filename with suffix sepparated! " + filename);
String id = filename.split(Pattern.quote("."))[0];
file file = fileRepository.findById(Long.parseLong(id));
File f = new File("/srv/Ressaca/locals/" + file.getId() + file.getExtension());
return new FileSystemResource(f);
}
谷歌搜索后,我找到了部分解决方案。使用这个解决方案,如果我输入一些类似localhost:8888/public/file/4.hello 或localhost:8888/public/file/4.jpj 的内容,它可以工作,但如果扩展名是一些真正的扩展名,比如(jpg、jpeg、mp3、mp4 等),Spring 引导会继续丢弃请求。
控制器在谷歌搜索后:
@RequestMapping(value = "public/file/{filename:.+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public FileSystemResource getPublicFile(@PathVariable("filename") String filename) {
System.out.println("filename " + filename);
String id = filename.split(Pattern.quote("."))[0];
file file = fileRepository.findById(Long.parseLong(id));
File f = new File("/srv/Ressaca/locals/" + file.getId() + file.getExtension());
return new FileSystemResource(f);
}
如何启用“真实文件扩展名”?
【问题讨论】:
-
非常感谢。我必须添加
consumes = MediaType.ALL_VALUE -
出于某种原因,Spring 考虑了 URL 文件扩展名,并使用来自扩展名的隐含媒体类型覆盖了接受标头中的值。 (至少这是我在 Spring 4.3.10.RELEASE 中看到的调试此问题。)例如,您有
.../file.txt,那么即使接受标头是application/json,它也会尝试匹配text/plain。解决方案是在浏览器中以训练/结束 URL,例如.../file.txt/
标签: java spring spring-mvc file-extension