Codementor Events

How to upload file to AWS S3 bucket using Spring boot

Published Aug 04, 2020

Provide below dependency in pom.xml:

<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk -->
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk</artifactId>
      <version>1.11.825</version>
    </dependency>

Below is the code snippet

import com.amazonaws.services.s3.AmazonS3;

public class S3Factory {
@Autowired
  AmazonS3 amazonS3Client;

  @Value("${s3.bucket.name}") // Default S3 bucket name. You need to create the bucket manually on AWS S3
  String defaultBucketName;

  @Value("${s3.default.folder}") // The folder inside S3 bucket where the file will be logically store.
  String defaultBaseFolder;
  
  public void uploadFile(String filedir, String name, byte[] content) {
    File file = new File(name);
    try (FileOutputStream iofs = new FileOutputStream(file)) {
      iofs.write(content);
      amazonS3Client.putObject(defaultBucketName, defaultBaseFolder + "/" + filedir + "/" + file.getName(), file);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Now your code is ready, now to use it autowire it in any service class like below:

@Autowired
S3Factory s3Factory;

And invoke it like below.
s3Factory.uploadFile(fileDir, fileName.toString(), file.getBytes());

Your file is now stored in S3 bucket.

Is not it awsome ?!!! Happy Coding 😃

Discover and read more posts from Rajib Halder
get started
post commentsBe the first to share your opinion
Show more replies