Brief introduction to AWS S3 bucket

Posted By : Amarnath Kumar | 29-Jul-2022

Amazon's S3 (Simple Storage Service) is a very reliable storage service for uploading and retrieving files.

It is very easy to integrate. In this tutorial, we will learn how we can integrate AWS S3 Bucket into the Spring Boot project for file uploading.


1. Maven Dependencies


First, we need to add Maven dependency for Amazon Java SDK.
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk ->
<dependency>
   <groupId>com.amazonaws</groupId>
   <artifactId>aws-java-sdk</artifactId>
   <version>1.11.880</version>
</dependencies>

Note: Check in mvn central repository for latest version.


2. Credentials
 

Create an AWS account and get the following credentials.

a.) ENDPOINT_URL

b.) BUCKET_NAME

c.) ACCESS_KEY

d.) SECRET_KEY


3. Create a Controller


Create a Rest Controller to receive the MultipartFile from the client for uploading to the S3 Bucket.


4. Initialize Amazon Client


Create a post-construction method to initialize the Amazon client.

@postconstruct
private void initializeAmazon() {
   AWSCCredentialsCredentials = new BasicAWSCCredentials(ACCESS_KEY, SECRET_KEY);
   this.s3client = AmazonS3ClientBuilder.standard(). WITH AREA (Area.AP_SOUTHEAST_1). WithCredentials(new AWSStaticCredentialsProvider(Credentials)). build();
}



5. MultipartFile to File


Create a method to convert multipart file to file. So, it can be uploaded to S3 Bucket.

private File ConvertMultiPartToFile(MultipartFile file) throws IOException {
   File convFile = new File(System.getProperty("java.io.tmpdir") + File.separator +Objects.requireNonNull(file.getOriginalFilename()));
   try {
      file.transferTo(convFile);
      LOGGER.info("File created successfully");
   } catch (IOException e) {
      LOGGER.error("Exception in File Convert Service");
  
   return conversion file;
}


6. Method to Generate File Names


This method will generate a filename for the file by which it can be recognized on the S3 bucket.

private String generateFileName(MultiPartFile multipart) {
   return new Date(). getTime() + "-" + Objects.requireNonNull(multiPart.getOriginalFilename()). replace("", "_");

}


7. Method of Uploading Files


This method uploads the file to the S3 bucket.

private void UploadFileTos3Bucket(String filename, File file) {
   s3client.putObject(
         new PutObjectRequest(BUCKET_NAME, fileName, file).withCannedAcl(CannedAccessControlList.PublicRead));
         }


8. S3. Create a Service to Upload Multipart Files to


This method takes a MultipartFile as input and uploads that file to the server and returns a URL by which we can access that particular file from the browser.

public String uploadFile(MultiPartFile multipartFile) {
   String file url = "";
   try {
     LOGGER.info("Amazon File Upload");
      File file = ConvertMultiPartToFile(MultiPartFile);
      String filename = generateFileName(multipartFile);
      fileUrl = ENDPOINT_URL + "/" + filename;
      uploadFileTos3bucket(filename, file);
      Utils.delete(file);
      return fileUrl;
   } catch (Exception e) {
      LOGGER.error("Error uploading file", e);
   return null;
   }



9. Method to Delete File from S3 Bucket


This method deletes the file from the S3 bucket.

public void deleteFileFromS3Bucket(String fileUrl) {
   String filename = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
   s3client.deleteObject(new DeleteObjectRequest(BUCKET_NAME, filename));
   }

About Author

Author Image
Amarnath Kumar

Amarnath is a spring web developer. He has good knowledge of Spring Cloud, Spring Boot, Spring MVC, Hibernate, and some template engines like jsp and thymleaf.

Request for Proposal

Name is required

Comment is required

Sending message..