我正在使用 FileSystemResource 和 Spring Webflux 来提供硬盘驱动器中的文件。
@GetMapping("/news/file")
fun getImage(@RequestParam name: String): FileSystemResource {
return FileSystemResource(propsStorage.path + "/" + name)
}
当用户请求未知文件时,应该捕获该文件并返回 404 错误。
但是我收到此错误:
java.nio.file.NoSuchFileException: C:\Users\SomeUser\Work\posts\32.jpg
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
不幸的是我不知道如何捕获错误。 如果你愿意的话,你可以用Java回答,我两种语言都听得懂。
最佳答案
您还可以利用 Spring FilesystemResource
api 存在避免 FileNotFoundException
fs =FileSystemResource(propsStorage.path + "/" + name)
if(fs.exists())
return fs
else
return new ResponseEntity<>("File Not Found", HttpStatus.NOT_FOUND);
我还看到您使用“/”作为分隔符,请注意,在 Windows 计算机上,文件分隔符是“”。因此,为了正确遵守,请使用 Paths.separator
关于java - Spring FileSystemResource NoSuchFileException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63884242/