Uploading Files to Amazon S3 Using Java

Cem Dırman
2 min readNov 29, 2023

--

In this article, we will explore how to upload files to Amazon S3 using Java. You can find detailed information about AWS S3.

First, we need to follow the steps below:

  1. Create a new bucket in AWS S3.
  2. Create a new user through Identity and Access Management (IAM).
  3. Generate an Access Key for the created user.
  4. Grant the user the ‘AmazonS3FullAccess’ permission. (If you skip this step, you will receive a 403 error.)

Now, let’s move on to the code.

Firstly, we need to add Amazon’s SDK for AWS S3 to our project.

implementation 'com.amazonaws:aws-java-sdk-s3:1.12.470'

Controller

@RequiredArgsConstructor
@RestController
public class DocumentController {

private final DocumentService documentService;

@PostMapping
public void saveImage(@RequestParam("file") MultipartFile file) {
documentService.upload(file);
}

}

This controller handles file upload requests and forwards them to the DocumentService.

Service

@RequiredArgsConstructor
@Service
public class DocumentService {

private final AmazonS3 amazonS3;
private final AWSClientConfig awsClientConfig;

public String upload(MultipartFile file) {
File localFile = convertMultipartFileToFile(file);

amazonS3.putObject(new PutObjectRequest(awsClientConfig.getBucketName(), file.getOriginalFilename(), localFile));

return file.getOriginalFilename();
}

private File convertMultipartFileToFile(MultipartFile file) {
File convertedFile = new File(file.getOriginalFilename());
try {
Files.copy(file.getInputStream(), convertedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
return convertedFile;
}

}

This service performs the necessary operations to upload a file to Amazon S3. The upload method converts the incoming MultipartFile into a File and then uploads this file to S3.

Configuration

@Configuration
@Getter
public class AWSClientConfig {

@Value("${aws.accessKey}")
private String accessKey;

@Value("${aws.secretAccessKey}")
private String secretAccessKey;

@Value("${aws.bucketName}")
private String bucketName;

private final Region region = Region.EU_CENTRAL_1; //kendi region bilginiz ile değiştirilmeli

@Bean
public AmazonS3 amazonS3() {
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretAccessKey);

return AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withRegion(region.toString())
.build();
}

@Bean
public TextractClient textractClient(){
return TextractClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretAccessKey)))
.region(region)
.build();
}

}

This configuration class creates the Amazon S3 client and other AWS clients. It also provides AWS credentials, region, and other connection settings.

We hope you find this information helpful.

--

--