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\32.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.
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
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.