AWS S3 With Spring Boot

Posted By : Rohan Dodeja | 27-May-2018

What is AWS S3 Bucket?

S3 bucket is a storage as a service of AWS i.e amazon web services, this service is used to store heterogeneous objects means any type of file or folder. S3 bucket is basically used to store data on a cloud with security, integrity, and Accessibility  Aws claims that file or folder will be accessible 99.9% of all the time 0.1% due to any un deterministic fault in the system, so most of the developers prefer to use to store data for there servers.

 

This service stores data in buckets used as containers to store data objects, you can make many buckets and buckets are individually have read and write access to different users so admin of S3 bucket has right to give access to any user for read only or write only or just read the properties of file only, this service has 1 great feature for security that is the file is secured and only accessible through secured link which is generated and destroyed after some time (after expiry time) so every time user access the file he has to ask for new secured link to access that file.

 

Following is the code sample used to integrate AWS S3 bucket in spring boot:-

Dependency:-

<dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.335</version>
</dependency>

Java file:-

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;


@Service
public class AwsS3Service {

    private static Logger logger = LoggerFactory.getLogger(AwsS3Service.class);
    @Autowired
    private EnvConfiguration envConfiguration;
    
    public Map<String, Object> uploadFileToAWSS3() {
        Map<String, Object> result = new HashMap<>();

        return result;
    }
    
    public String uploadDocumentOnAwsBucket(MultipartFile document) throws Exception {
        String uploadedFileLocation = envConfiguration.getAwsS3BucketName();
        String updatedFileName = null;
        String originalFileName = document.getOriginalFilename();
        int dot = originalFileName.lastIndexOf(".");
        String extension = (dot == -1) ? "" : originalFileName.substring(dot + 1);
        updateFNme = UUID.randomUUID()

                        .toString()  +  "."  +  extension;
        try {
            InputStream is = document.getInputStream();
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(is.available());
            AmazonS3 s3Client = s3Authentication(new BasicAWSCredentials(envConfiguration.getAwsS3AccessKey(),envConfiguration.getAwsS3SecretKey()));
            s3Client.putObject(new PutObjectRequest(uploadedFileLocation, updatedFileName, is, meta)
                    .withCannedAcl(CannedAccessControlList.Private));
            is.close();
            logger.info("uploaded document to bucket: " + updatedFileName);
            return updatedFileName;
        } catch (Exception ex) {
            logger.error("unable to upload file on bucket: " + ex.getMessage());
            throw new Exception("Unable to upload document");
        }
    }

    public AmazonS3 s3Authentication(AWSCredentials creds) {
        AmazonS3 s3client = AmazonS3ClientBuilder
                  .standard()
                  .withCredentials(new AWSStaticCredentialsProvider(creds))
                  .withRegion(envConfiguration.getAwsS3BucketRegion())
                  .build();
        logger.info("s3Client "+s3client);
        return s3client;
    }

    public String generatePreSignedUrl(String fileName) {
        AmazonS3 s3client = s3Authentication(new BasicAWSCredentials(envConfiguration.getAwsS3AccessKey(),envConfiguration.getAwsS3SecretKey()));
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(envConfiguration.getAwsS3BucketName(), fileName);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET);
        Long expiryTimeinMillis = System.currentTimeMillis() + Long.parseLong(envConfiguration.getAwsS3LinkExpiryMillis());
        Date currentDate = new Date();
        currentDate.setTime(expiryTimeinMillis);
        generatePresignedUrlRequest.setExpiration(currentDate);
        URL url = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }
}

 

Hope this code sample helps you integrate it in your project.

About Author

Author Image
Rohan Dodeja

Rohan is a bright web app Lead developer and have experience on Java, J2EE, REDIS, SQL. His hobbies are gaming and Travelling.

Request for Proposal

Name is required

Comment is required

Sending message..