$ show spring-guides/gs-uploading-files
This repository is a Spring Guide tutorial demonstrating how to build a Spring Boot web application that accepts HTTP multipart file uploads. It contains four project variants: initial and complete versions in both Java and Kotlin, each with Maven and Gradle build files. The complete version adds a FileUploadController with endpoints for listing uploaded files, serving them as downloads, and handling uploads, plus a StorageService abstraction backed by a FileSystemStorageService that writes files to a configurable local directory (default 'upload-dir'). A Thymeleaf template provides a simple HTML upload form. The application is a small monolith: Spring MVC controllers handle GET / (list files), POST / (store uploaded file), and GET /files/{filename} (download with Content-Disposition). The storage layer uses java.nio.file APIs and includes a path traversal protection check that rejects filenames escaping the root directory. Upload size limits are configured via spring.servlet.multipart properties. Tests cover controller behavior with MockMvc, storage service security cases, and full integration tests using RestTestClient with redirect handling. This is educational sample code, not a production service. It demonstrates clean separation between web layer and storage abstraction, and the complete version includes meaningful security and testing patterns that can be reused in real projects. The code is actively maintained, uses current Spring Boot 4.0.x and Java 17, and is well-suited as a reference for implementing file upload endpoints.
The LLM identified 3 files worth highlighting for reuse:
Implements the StorageService interface using java.nio.file. Validates the configured location, rejects empty uploads, normalizes the destination path and verifies it stays under the root to prevent directory traversal, copies the MultipartFile stream with REPLACE_EXISTING, lists files with Files.walk, and serves resources via UrlResource. This is a self-contained, extractable file-storage service with a security check that is often missing in naive implementations.
Unit tests for the storage service covering empty location, saving/loading, and path traversal attempts (relative and absolute). Includes a Linux-specific test for backslash filenames. This is a reusable test pattern for validating file storage security.
Integration tests using Spring Boot's RestTestClient. The upload test builds a custom ClientHttpRequestFactory with redirects disabled to assert the 302 and Location header, and the download test verifies Content-Disposition and body. Demonstrates a non-obvious technique for testing multipart endpoints without following redirects.