Retrieving Files

Now that we can store files on disk, we need to implement the functionality to retrieve them. This will complete our StorageService implementation by adding the loadAsResource method.

Understanding Spring Resources

Spring's Resource abstraction provides a unified way to handle different types of resources, including files.

The Resource interface offers methods to check if a resource exists and to read its contents.

For file system resources, we use Spring's UrlResource class, which handles files through URLs and file paths.

Implementing File Retrieval

Let's implement the loadAsResource method in our FileSystemStorageService class:

@Override public Optional<Resource> loadAsResource(String filename) { try { // Resolve the file path relative to our root location Path file = rootLocation.resolve(filename); // Create a Resource object from the file path Resource resource = new UrlResource(file.toUri()); // Check if the resource exists and is readable if (resource.exists() || resource.isReadable()) { return Optional.of(resource); } else { return Optional.empty(); } } catch (MalformedURLException e) { log.debug("Could not read file: " + filename, e); return Optional.empty(); } }

The method follows these steps:

  • Converts the filename to a full file path using resolve
  • Creates a UrlResource from the file path
  • Checks if the file exists and is readable
  • Returns the resource wrapped in an Optional

Error Handling

We use Optional to handle cases where the file might not exist.

This approach is better than throwing exceptions for missing files, as a missing file is a valid scenario rather than an error condition.

The method catches MalformedURLException and returns an empty Optional instead of throwing an exception.

This makes the API more user-friendly as clients can easily check if a file exists using Optional's methods.

Summary

  • Implemented loadAsResource method to retrieve stored files
  • Used Spring's Resource interface for file handling
  • Implemented error handling with Optional
  • Used UrlResource to represent file system resources
  • Added logging for debugging file access issues
© 2026 Devtiro Ltd. All rights reserved