Photo Upload Endpoint
In this lesson, we'll create a REST API endpoint that allows users to upload photos to our restaurant review platform.
We'll build on our existing photo services and create a controller that handles the upload process through a simple HTTP request.
Creating the Controller
Controllers in Spring Boot handle incoming HTTP requests and direct them to the appropriate service layers.
Let's create a new package com.devtiro.restaurant.controllers and add our PhotoController class:
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/photos")
public class PhotoController {
private final PhotoService photoService;
private final PhotoMapper photoMapper;
@PostMapping
public PhotoDto uploadPhoto(
@RequestParam("file") MultipartFile file) {
Photo savedPhoto = photoService.uploadPhoto(file);
return photoMapper.toDto(savedPhoto);
}
}Let's break down the key components of our controller:
- The
@RestControllerannotation tells Spring this class handles REST requests @RequestMapping("/api/photos")sets the base URL path for all endpoints in this controller@RequiredArgsConstructorautomatically creates a constructor for our final fields- The
uploadPhotomethod is mapped to POST requests using@PostMapping @RequestParam("file")binds the uploaded file to theMultipartFileparameter
Understanding MultipartFile
Spring's MultipartFile interface represents an uploaded file in a multipart request.
It provides methods to:
- Access the original filename
- Get the file's content type
- Read the file's contents
- Get the file size
The interface works seamlessly with our existing PhotoService which we implemented in previous lessons.
Testing the Endpoint
Once you've implemented the controller, you can test it using any HTTP client that supports file uploads.
Here's what happens when you make a request:
- The client sends a POST request to
/api/photoswith the file in the request body - Our controller receives the file and passes it to the
PhotoService - The
PhotoServicegenerates a UUID and stores the file - The file is saved to disk using our
StorageService - A
PhotoDtocontaining the UUID and metadata is returned to the client
Summary
- Created
PhotoControllerto handle REST API requests - Implemented the
/api/photosendpoint for photo uploads - Used Spring's
MultipartFilefor file handling - Connected the controller to our
PhotoService - Returns a
PhotoDtowith the photo's UUID and metadata