Spring Boot
Image Storage
Web Application
External Location
Tutorial

How to specify external location for image store in Spring Boot 2.0 web app?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

In a Spring Boot web application, storing uploaded images outside the packaged application directory is usually the right design. It avoids losing files on redeploy, keeps the application artifact immutable, and makes storage paths configurable per environment. The clean approach is to externalize the storage directory into configuration, write files through a service, and expose them through a mapped resource handler or controller.

Put the Storage Path in Configuration

Do not hardcode filesystem paths inside controllers. Use a property and bind it once.

properties
app.images.dir=/opt/myapp/images

Then map it into a typed configuration class:

java
1import org.springframework.boot.context.properties.ConfigurationProperties;
2
3@ConfigurationProperties(prefix = "app.images")
4public class ImageStorageProperties {
5    private String dir;
6
7    public String getDir() {
8        return dir;
9    }
10
11    public void setDir(String dir) {
12        this.dir = dir;
13    }
14}

That keeps the actual location environment-specific and easy to override.

Save Files Through a Dedicated Service

The service should normalize paths, create directories if needed, and reject dangerous filenames.

java
1import java.io.IOException;
2import java.io.InputStream;
3import java.nio.file.Files;
4import java.nio.file.Path;
5import java.nio.file.Paths;
6import java.nio.file.StandardCopyOption;
7import org.springframework.web.multipart.MultipartFile;
8
9public class ImageStorageService {
10    private final Path root;
11
12    public ImageStorageService(ImageStorageProperties properties) throws IOException {
13        this.root = Paths.get(properties.getDir()).toAbsolutePath().normalize();
14        Files.createDirectories(this.root);
15    }
16
17    public String save(MultipartFile file) throws IOException {
18        String filename = Path.of(file.getOriginalFilename()).getFileName().toString();
19        Path target = root.resolve(filename).normalize();
20
21        if (!target.startsWith(root)) {
22            throw new IllegalArgumentException("Invalid file path");
23        }
24
25        try (InputStream in = file.getInputStream()) {
26            Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
27        }
28        return filename;
29    }
30}

The startsWith(root) check prevents path traversal through malicious upload names.

Expose the External Directory as Static Content

If you want images to be served by Spring MVC, register a resource handler that points to the external filesystem directory.

java
1import org.springframework.context.annotation.Configuration;
2import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
3import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
4
5@Configuration
6public class StaticResourceConfig implements WebMvcConfigurer {
7    private final ImageStorageProperties properties;
8
9    public StaticResourceConfig(ImageStorageProperties properties) {
10        this.properties = properties;
11    }
12
13    @Override
14    public void addResourceHandlers(ResourceHandlerRegistry registry) {
15        String location = "file:" + properties.getDir() + "/";
16        registry.addResourceHandler("/images/**")
17                .addResourceLocations(location);
18    }
19}

With that in place, a file stored as example.png under the configured directory becomes available at /images/example.png.

Keep Deployment and Permissions in Mind

External storage only works if the application process can read and write the directory. In real deployments, check:

  1. directory ownership
  2. filesystem permissions
  3. mounted volume availability in containers

If the path is invalid or not writable, fail fast at startup or during the first save operation with a clear error rather than a generic 500 response.

When Filesystem Storage Is Enough

External filesystem storage is a good fit for a single server or a simple internal application. Once you need multiple instances, shared storage or object storage such as S3 usually becomes a better design. The application code still benefits from the same abstraction, because only the backing storage service changes.

That is another reason to avoid putting filesystem logic directly inside controllers. A storage service gives you a migration path when local disk stops being the right backend.

Common Pitfalls

  • Hardcoding upload directories in controllers instead of configuration.
  • Writing files under src/main/resources and losing them on redeploy.
  • Trusting the original filename without normalization and path checks.
  • Forgetting to configure a resource handler or controller to serve the files back.
  • Deploying to containers without mounting a persistent writable directory.

Summary

  • Store image paths in configuration, not in code.
  • Write files through a dedicated service that validates and normalizes paths.
  • Use a resource handler to expose the external directory over HTTP when needed.
  • Check directory permissions and persistence strategy in deployment.
  • Filesystem storage is fine for simple deployments, but abstraction helps future migration to shared or cloud storage.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms