英文:
Spring FileSystemResource NoSuchFileException
问题
以下是翻译好的内容:
我正在使用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.jpg
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
不幸的是,我不知道如何捕获这个错误。您可以使用Java回答,我可以理解这两种语言。
英文:
I am using FileSystemResource and Spring Webflux to serve files from the hard drive.
@GetMapping("/news/file")
fun getImage(@RequestParam name: String): FileSystemResource {
return FileSystemResource(propsStorage.path + "/" + name)
}
When the user requests an unknown file, it should be catched and an 404 error should be returned.
However I get this error:
java.nio.file.NoSuchFileException: C:\Users\SomeUser\Work\posts.jpg
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Unfortunately I don't know how to catch the error.
You can answer in Java if you want, I can understand both languages.
答案1
得分: 3
你还可以利用Spring的FilesystemResource
API的exists
方法来避免FileNotFoundException
:
fs = FileSystemResource(propsStorage.path + "/" + name);
if (fs.exists())
return fs;
else
return new ResponseEntity<>("文件未找到", HttpStatus.NOT_FOUND);
另外,我注意到你在使用'/'
作为分隔符,但请注意,在Windows机器上,文件分隔符是'\'
。因此,为了正确兼容,请使用Paths.separator
。
英文:
Also you can make use of the spring FilesystemResource
api exists method to avoid the FileNotFoundException
fs =FileSystemResource(propsStorage.path + "/" + name)
if(fs.exists())
return fs
else
return new ResponseEntity<>("File Not Found", HttpStatus.NOT_FOUND);
Also I saw that you used '/' as a separator, please note that on windows machines the file separator is ''. So for complying correctly use Paths.separator
答案2
得分: 0
你可以为 java.nio.file.NoSuchFileException
编写一个 @ExceptionHandler
方法,并返回 404 响应。
以下是 Java 代码,你可以将其翻译成 Kotlin:
@ExceptionHandler(NoSuchFileException::class)
fun handleUnexpectedRollbackException(exception: NoSuchFileException): ResponseEntity<String> {
LOGGER.error("File not found", exception)
return ResponseEntity("File Not Found", HttpStatus.NOT_FOUND)
}
英文:
You can have an @ExceptionHandler
method for java.nio.file.NoSuchFileException
and return 404 response.
Below is in Java you can translate in kotlin.
@ExceptionHandler(NoSuchFileException.class)
public ResponseEntity<String> handleUnexpectedRollbackException(NoSuchFileException exception) {
LOGGER.error("File not found",exception);
return new ResponseEntity<>("File Not Found", HttpStatus.NOT_FOUND);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论