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));
}
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
Amarnath Kumar
Amarnath Kumar is a highly skilled Backend Developer with over 2+ years of experience in the industry. He is well-versed in the latest technologies and has hands-on experience in Core Java, Spring-Boot, Spring-Security, Hibernate, Apache Kafka messaging queue, and Blockchain application development based on Ethereum, Tron, and Relational databases like MySQL and PostgreSQL. He is proficient in API implementations, Web Services, Socket programming, and code enhancements. He has contributed significantly to the company's success through his work on various client projects, including Wethio-Exchange, Hedgex Exchange, and many more. He enjoys reading and exploring new technologies to enhance his knowledge and expertise.