Why dont you take a look at Spring Content. This is designed to do exactly what you are trying to do.
Assuming you are using Spring Data to store each user profile you might add it to your project as follows:
pom.xml
<!-- Java API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-fs-boot-starter</artifactId>
<version>0.4.0</version>
</dependency>
<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest-boot-starter</artifactId>
<version>0.4.0</version>
</dependency>
FilesystemConfiguration.java
@Configuration
public class FilesystemConfiguration {
@Bean
File filesystemRoot() {
try {
return new File("/path/to/your/user/profile/image/store");
} catch (IOException ioe) {}
return null;
}
@Bean
FileSystemResourceLoader fileSystemResourceLoader() {
return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
}
}
User.java
@Entity
public class User {
@Id
@GeneratedValue
private long id;
...other existing fields...
@ContentId
private String contentId;
@ContentLength
private long contentLength = 0L;
@MimeType
private String mimeType = "text/plain";
...
}
UserContentStore.java
@StoreRestResource(path="userProfileImages")
public interface UserContentStore extends ContentStore<User, String> {
}
This is all you need to do to get REST Endpoints that will allow you to store and retrieve content associated with each User. How this actually works is very much like Spring Data. When your application starts Spring Content will see the spring-content-fs-boot-starter
dependencies and know that you want to store content on the filesystem. It will also inject a Filesystem-based implementation of the UserContentStore
interface. It will also see the spring-content-rest-boot-starter
and will inject REST endpoints that talk to the content store interface. Meaning you don't have to write any of this code yourself.
So, for example:
curl -X POST /userProfileImages/{userId} -F "file=@/path/to/image.jpg"
will store the image on the filesystem and associate it with the user entity whose id is userId
.
curl /userProfileImages/{userId}
will fetch it again and so on...supports full CRUD and video streaming too actually.
You could also decide to store the contents elsewhere like in the database (as someone commented), or in S3 by swapping the spring-content-fs-boot-starter
dependency for the appropriate Spring Content Storage module. Examples for every type of storage are here.