Amazon Web Services (AWS) provides a reliable, scalable, and affordable cloud computing platform that allows businesses to store and retrieve any amount of data. One of the most widely used services in AWS is Amazon S3 (Simple Storage Service), which provides a robust platform for storing objects. In this tutorial, we will guide you through the process of uploading files to AWS S3 using Java Spring Boot.
Why Use Amazon S3?
- Scalability: S3 automatically scales to handle any amount of data.
- Durability: S3 is designed for 99.999999999% durability over a given year.
- Security: You can restrict access to your objects using AWS IAM roles or S3 bucket policies.
Prerequisites
Before diving into the implementation, ensure you have the following:
- AWS Account: Sign up for an AWS account if you don’t have one.
- AWS Access Keys: These are required to access your S3 bucket.
- S3 Bucket: Create an S3 bucket where you will upload files.
- Java Development Kit (JDK) installed on your machine.
- Spring Boot: Set up a Spring Boot project. You can use Spring Initializr to bootstrap the project.
Setting Up AWS S3 Credentials
-
Create AWS Access Keys:
- Go to the AWS IAM Console.
- Create a new IAM user with programmatic access.
- Attach the AmazonS3FullAccess policy to the user.
- Download the Access Key ID and Secret Access Key.
-
Create an S3 Bucket:
- Go to the S3 Console.
- Create a new bucket (choose a globally unique name).
- Choose the region and configure permissions as needed.
Project Setup
Dependencies
Add the following dependencies to your pom.xml
file:
xml
<dependencies>
<!-- Spring Web Dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- AWS SDK for Java -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
</dependency>
</dependencies>
Configuration
Create a file application.properties
to store your AWS S3 configuration:
aws.accessKeyId=YOUR_ACCESS_KEY_ID
aws.secretKey=YOUR_SECRET_ACCESS_KEY
aws.s3.bucket=YOUR_BUCKET_NAME
aws.s3.region=YOUR_AWS_REGION
S3 Configuration Class
Create a class AmazonS3Config.java
to configure the Amazon S3 client:
package com.example.s3demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
@Configuration
public class AmazonS3Config {
@Bean
public S3Client s3Client() {
AwsBasicCredentials awsCreds = AwsBasicCredentials.create(
"YOUR_ACCESS_KEY_ID",
"YOUR_SECRET_ACCESS_KEY"
);
return S3Client.builder()
.region(Region.of("YOUR_AWS_REGION"))
.credentialsProvider(StaticCredentialsProvider.create(awsCreds))
.build();
}
}
Service for S3 File Upload
Now, create a service class S3Service.java
to handle the file upload:
package com.example.s3demo.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import java.io.IOException;
import java.nio.file.Paths;
@Service
public class S3Service {
private final S3Client s3Client;
@Value("${aws.s3.bucket}")
private String bucketName;
public S3Service(S3Client s3Client) {
this.s3Client = s3Client;
}
public String uploadFile(MultipartFile file) throws IOException {
String keyName = Paths.get(System.currentTimeMillis() + "_" + file.getOriginalFilename()).toString();
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
s3Client.putObject(putObjectRequest, RequestBody.fromBytes(file.getBytes()));
return "File uploaded successfully: " + keyName;
}
}
File Upload Controller
Create a controller FileUploadController.java
to handle the file upload request:
package com.example.s3demo.controller;
import com.example.s3demo.service.S3Service;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/s3")
public class FileUploadController {
private final S3Service s3Service;
public FileUploadController(S3Service s3Service) {
this.s3Service = s3Service;
}
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
String response = s3Service.uploadFile(file);
return ResponseEntity.ok(response);
} catch (Exception e) {
return ResponseEntity.status(500).body("Error uploading file: " + e.getMessage());
}
}
}
Testing the File Upload
Once your Spring Boot application is running, you can test the file upload with Postman or cURL.
curl -X POST http://localhost:8080/api/s3/upload \
-F 'file=@/path/to/your/file'
Using Postman:
- Select POST and enter http://localhost:8080/api/s3/upload.
- Go to the Body tab, select form-data, and add a file with the key file.
- Select a file from your local machine and click Send.