Uploading Retrieving Photos
Building on our previous work with the StorageService, we'll now create a dedicated service for handling photo operations, which will generate unique identifiers for photos and maintain additional metadata about uploaded images.
The Photo Service Interface
Let's start by defining a clear contract for photo operations through an interface.
package com.devtiro.restaurant.services;
import com.devtiro.restaurant.domain.entities.Photo;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.util.Optional;
public interface PhotoService {
Photo uploadPhoto(MultipartFile file);
Optional<Resource> getPhotoAsResource(String id);
}The interface defines two main operations: uploading a new photo and retrieving an existing one.
The uploadPhoto method returns a Photo entity that contains metadata about the uploaded file.
The getPhotoAsResource method returns an Optional<Resource> to handle cases where the photo might not exist.
Implementing the Photo Service
Now let's implement the photo service, leveraging our existing StorageService.
@Service
@RequiredArgsConstructor
public class PhotoServiceImpl implements PhotoService {
private final StorageService storageService;
@Override
public Photo uploadPhoto(MultipartFile file) {
// Generate a unique ID for the photo
String photoId = UUID.randomUUID().toString();
// Store the file and get its URL
String url = storageService.store(file, photoId);
// Create and populate the photo entity
Photo photo = new Photo();
photo.setUrl(url);
photo.setUploadDate(LocalDateTime.now());
return photo;
}
@Override
public Optional<Resource> getPhotoAsResource(String id) {
return storageService.loadAsResource(id);
}
}The implementation delegates the actual file operations to the StorageService we created earlier.
For photo uploads, we generate a unique identifier using UUID to ensure no two photos have the same ID.
We store additional metadata like the upload date, which will be useful for tracking and managing photos.
Summary
- Implemented
PhotoServiceinterface defining upload and retrieval operations - Created
PhotoServiceImplto manage photo storage and retrieval - Used
UUIDto generate unique identifiers for photos - Leveraged existing
StorageServicefor file operations