Spring Boot - AWS S3 integration
Spring Boot is a popular Java-based framework used for building standalone, production-grade applications. It provides a wide range of features, such as auto-configuration, embedded servers, and a simplified configuration model, to help developers quickly build and deploy applications.
Amazon Simple Storage Service (S3) is a cloud-based object storage service provided by Amazon Web Services (AWS). It allows users to store and retrieve large amounts of data, such as images, videos, and documents, from anywhere in the world.
Here's an example of how to integrate AWS S3 with a Spring Boot application using the AWS SDK for Java:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.61</version>
</dependency>
2. Add AWS S3 Configuration Properties in application.properties:
Recommended by LinkedIn
aws.accessKeyId=<your_access_key>
aws.secretKey=<your_secret_key>
aws.region=<your_aws_region>
aws.s3.bucketName=<your_bucket_name>
3. Create a S3Service class to interact(upload, delete and download) with S3:
@Service
public class S3Service {
private final AmazonS3 amazonS3;
private final String bucketName;
public S3Service(AmazonS3 amazonS3, @Value("${aws.s3.bucketName}") String bucketName) {
this.amazonS3 = amazonS3;
this.bucketName = bucketName;
}
public void uploadFile(String key, File file) {
amazonS3.putObject(bucketName, key, file);
}
public void deleteFile(String key) {
amazonS3.deleteObject(bucketName, key);
}
public S3Object downloadFile(String key) {
return amazonS3.getObject(bucketName, key);
}
}
4. Create a Controller class to handle file uploads:
@RestController
public class S3Controller {
private final S3Service s3Service;
public S3Controller(S3Service s3Service) {
this.s3Service = s3Service;
}
@PostMapping("/upload")
public void uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
File convertedFile = convertMultiPartFileToFile(file);
s3Service.uploadFile(file.getOriginalFilename(), convertedFile);
convertedFile.delete();
}
private File convertMultiPartFileToFile(MultipartFile file) throws IOException {
File convertedFile = new File(file.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(convertedFile);
fos.write(file.getBytes());
fos.close();
return convertedFile;
}
}
With this code, we can able to interact(upload, delete and download) to our S3 bucket from the Spring Boot application.
Could you be having a repository for this solution?
Super brother👍
Great Stuff 👍
Good work Jasberraja P