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
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rohan Dodeja
Rohan is a bright web app Lead developer and have experience on Java, J2EE, REDIS, SQL. His hobbies are gaming and Travelling.