How to Upload Files to Amazon S3 Buckets in Spring Boot

In Amazon S3, files or any other data are stored as objects in buckets. A bucket is nothing but a logical container for objects in S3.

Follow the steps below to complete this example:

Adding Dependency

To upload files to S3, you will need to add the AWS Java SDK For Amazon S3 dependency to your application. Here is the Maven repository for Amazon S3 SDK for Java.

Gradle Dependency

Add the following dependency to the build.gradle file:


implementation group: 'com.amazonaws', name: 'aws-java-sdk-s3', version: '1.12.158'
Maven Dependency

Add the following dependency to the pom.xml file:



Add Configurations

First, add the following credentials to your resources/application.properties configuration file:


server.port=8080

aws.access-key = your aws access key here
aws.access-secret-key = your aws secret key here
aws.region = us-east-1

Create Configuration Class

Create a configuration Java class for the AmazonS3 Client:


package com.s3.sample.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;

@Configuration
public class AwsConfig {

	private String awsAccessKey;
	private String awsAccessSecretKey;
	private String awsRegion;

	public AwsConfig(@Value(value = "${aws.access-key}") String awsAccessKey,
			@Value(value = "${aws.access-secret-key}") String awsAccessSecretKey,
			@Value(value = "${aws.region}") String awsRegion) {
		this.awsAccessKey = awsAccessKey;
		this.awsAccessSecretKey = awsAccessSecretKey;
		this.awsRegion = awsRegion;
	}

	public AWSStaticCredentialsProvider getAwsCredentialsProvider() {
		BasicAWSCredentials awsCred = new BasicAWSCredentials(this.awsAccessKey, this.awsAccessSecretKey);
		return new AWSStaticCredentialsProvider(awsCred);
	}

	@Bean
	public AmazonS3 getAmazonS3Client() {
		return AmazonS3ClientBuilder.standard().withRegion(this.awsRegion).withCredentials(getAwsCredentialsProvider())
				.build();
	}
}

Create Service

Create a service class with a method to upload a file to Amazon S3 bucket:

amazon-s3-sample/src/main/java/com/sample/s3/service/S3UploadServiceExample.java

package com.s3.sample.demo.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;

@Service
public class S3UploadServiceExample {

	private String s3BaseUrl = "https://s3-us-east-1.s3.amazonaws.com/";
   
	private String bucketName = "my-test-bucket";

	private String folderName = "/myfolder/images/";

	@Autowired
	private AmazonS3 s3Client;

	public Map<String, String> uploadFileToS3(MultipartFile multipartfile) {
        
		Map<String, String> response = new HashMap<>();

		if (multipartfile != null && !multipartfile.isEmpty()) {

			String filePathName = multipartfile.getOriginalFilename();

			File file = new File(filePathName);

			try (FileOutputStream fos = new FileOutputStream(file)) {

				if (!file.exists()) {
					file.createNewFile();
				}

				fos.write(multipartfile.getBytes());
				fos.flush();

				/* uploading file to S3 */
				s3Client.putObject(new PutObjectRequest(bucketName, folderName + "/" + file.getName(), file)
						.withCannedAcl(CannedAccessControlList.PublicRead));

				/* Url location of the uploaded file in S3. You should save it in database */
                String s3FileAccessUrl = s3BaseUrl.concat(bucketName).concat(folderName).concat(file.getName())
						.replaceAll("\\s", "+");

				response.put("fileUrl", s3FileAccessUrl);

				file.delete();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return response;
	}

}

Create Web Controller

Create a controller class with a REST API endpoint to upload files to S3:

spring-boot-s3-sample/src/main/java/com/s3/sample/demo/controller/AmazonS3UploadExampleController.java

package com.s3.sample.demo.controller;

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.s3.sample.demo.service.S3UploadServiceExample;

@RestController
@RequestMapping(value = "/api/files")
public class AmazonS3UploadExampleController {

	@Autowired
	private S3UploadServiceExample s3UploadServiceExample;

	@PostMapping(value = "/upload")
	public ResponseEntity<Map<String, String>> uploadFile(MultipartFile multipartfile) {

		return ResponseEntity.ok(s3UploadServiceExample.uploadFileToS3(multipartfile));
	}
}

The code is complete. You can run and test your application.