Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
Anyone can send anything: a text file, a fake .png, a 3 MB file. PhotoStorage checks the type, reads the bytes with ImageIO, fits the picture inside 256 by 256 and saves it as a random UUID name. The Account keeps only that name, and /photos serves the folder.
What you will learn
- Receive a MultipartFile from a multipart/form-data form
- Reject wrong files by content type and by actually reading the bytes with ImageIO
- Resize the image and save it under a random UUID name
- Serve the uploads folder at /photos with a resource handler and cap the size at 2 MB
Before you start
- Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot
The profile page gets a bio and a photo. The bio is easy. The photo is a file from a stranger: Emma picks emma.png, but anyone can send a text file, a fake .png that isn't a picture at all, or a huge file. So the server checks the file, shrinks it, and keeps it under its own name.
A photo desk at the club
The clerk asks: is it a PNG or a JPEG? Is it really a picture? Then trims it to size and files it under a number, not under the name on the envelope. In our code, the photo desk is PhotoStorage, the drawer is the uploads folder, and the number goes into the Account's photo field, which holds only a file name, never the picture.
PhotoStorage: the checks
@Service
public class PhotoStorage {
public static final String WRONG_TYPE = "Please choose a PNG or JPEG image";
private static final int MAX_SIDE = 256;
private final Path folder;
public PhotoStorage(@Value("${blog.uploads}") String folder) {
this.folder = Path.of(folder);
}
// returns the file name it saved, e.g. 3f2c...png
public String save(MultipartFile file) throws IOException {
if (!List.of("image/png", "image/jpeg").contains(file.getContentType())) {
throw new IllegalArgumentException(WRONG_TYPE);
}
BufferedImage image;
try (InputStream in = file.getInputStream()) {
image = ImageIO.read(in); // null when the bytes are not a picture, whatever the name says
}
if (image == null) {
throw new IllegalArgumentException(WRONG_TYPE);
}
Files.createDirectories(folder);
String name = UUID.randomUUID() + ".png"; // our own name: never the file name the browser sent
ImageIO.write(resize(image), "png", folder.resolve(name).toFile());
return name;
}
// fit inside 256 x 256, keep the shape
private BufferedImage resize(BufferedImage image) {
double scale = Math.min(1.0, (double) MAX_SIDE / Math.max(image.getWidth(), image.getHeight()));
int width = Math.max(1, (int) Math.round(image.getWidth() * scale));
int height = Math.max(1, (int) Math.round(image.getHeight() * scale));
BufferedImage small = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = small.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
return small;
}
}
First check: the content type must be image/png or image/jpeg. Second check: ImageIO.read returns null when the bytes aren't a picture, whatever the name says. Then our own name, a random UUID plus .png, never the name the browser sent. resize fits the image inside 256 by 256 and keeps its shape, so a 640 by 400 picture becomes 256 by 160.
The controller and the form
@PostMapping("/account/photo")
public String uploadPhoto(Principal principal, @RequestParam MultipartFile photo,
RedirectAttributes redirect) throws IOException {
try {
accountService.setPhoto(principal.getName(), photoStorage.save(photo));
redirect.addFlashAttribute("message", "Your photo is saved");
} catch (IllegalArgumentException e) {
redirect.addFlashAttribute("error", e.getMessage());
}
return "redirect:/account";
}
photoStorage.save runs first because its answer goes into setPhoto; a select finds Emma's account and an update writes the file name into the photo column. A wrong file throws IllegalArgumentException, and its message goes back as a flash error on the profile page.
<form class="form-card" th:action="@{/account/photo}" method="post" enctype="multipart/form-data">
<label for="photo">Photo (PNG or JPEG, up to 2 MB)</label>
<input id="photo" type="file" name="photo" accept="image/png, image/jpeg">
<button class="button-link" type="submit">Upload photo</button>
</form>
The form needs enctype="multipart/form-data". Without it the browser sends only the file name, not the bytes. On the page, th:if shows the image when there's a photo and th:unless shows the first letter of the name when there isn't.
Showing a file from the disk
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final String uploads;
public WebConfig(@Value("${blog.uploads}") String uploads) {
this.uploads = uploads;
}
// /photos/abc.png is read from the uploads folder on disk
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/photos/**")
.addResourceLocations("file:" + uploads + "/");
}
}
spring:
servlet:
multipart:
max-file-size: 2MB # a bigger file is refused before our code runs
blog:
uploads: uploads # the folder for profile photos (next to where the app runs)
Any URL under /photos is read from the uploads folder. /photos/** is added to the open rules in SecurityConfig, so visitors see the photos too.
Three files we don't keep
notes.txt has the wrong type and stops at the first check with "Please choose a PNG or JPEG image". fake.png claims image/png but is 16 bytes of text, so ImageIO.read gives null and the same message comes back. huge.png, 3 MB, is over the limit and refused before our code even runs: the app shows its own 413 page, and no SQL runs at all. The name says png? We still read the bytes before we believe it.
Emma's photo, everywhere
Emma's profile shows her photo and bio, and the same photo sits next to her name on her posts. The file comes from /photos/... with status 200, type image/png, 256 by 160. Noah has no photo yet, so his posts show the letter N.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
