This is part 4 of Developing Instagram Clone series, other parts are linked below
In real, the responsibilities of the media service should be to upload an image to a cloud object storage like Amazon S3 and stores a metadata about the image in a data store, MongoDB in our case.
To avoid paying for object storage services, media service has an additional responsibility (hack) to store the images on file system and to serve the images.
As always we start by cloning the Media service from GitHub.
The first step we need is to configure spring to serve static content in order to generate a URL to access each uploaded image.
Let’s look into StaticResourceConfiguration.
@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {
@Value("${file.upload-dir}")
private String uploadDirectory;
@Value("${file.path.prefix}")
private String filePathPrefix;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler(filePathPrefix + "/**")
.addResourceLocations("file:" + uploadDirectory);
}
}
Here we configure spring to map the following URL
http://{host}:{port}/{filePathPrefix}/{image_filename}
to
{uploadDirectory}/{image_filename}
Let’s have a look into application.yml file to give a concrete example.
spring:
...
file:
upload-dir: /home/amr/insta-clone-images/
path:
prefix: /images
server:
port: 8000
Line 5, sets the upload directory, don’t forget to change this to an existing directory on your machine.
The prefix is set to “/images” and service port to 8080.
Let’s assume we that the image file name is “image1.jpg” , the above would translates to
http://localhost:8080/images/image1.jpg
This will be mapped to the following filesystem path
/home/amr/insta-clone-images/image1.jpg
#microservices #cloud #mongodb #aws #developer