How To Upload File In AWS S3(Simple Storage Service) Bucket.
Today Agenda: How to upload and delete a file from the S3 bucket.
In the next ten minutes, you can easily configure the S3 bucket in your application.
What Is AWS S3 Bucket
Amazon S3 has a simple web services interface that you can use to store and retrieve any amount of data like images, files, and videos. Whenever you upload the data on S3 it will upload your data in the specified path and creates a unique link for data, using this link you can access data over the internet and also save into the Database for future use.
Let’s Start
Required Tools
Maven
STS
JDK 8
(Attention)Read Each Line carefully
Add AWS Jdk Dependency In Pom.xml
<dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk</artifactId> <version>1.11.163</version> </dependency>
Now Add The AWS S3 Authentication Details In application.properties
#AWS S3 Credentials aws.access.key.id= aws.access.key.secret= aws.region= aws.s3.247tuts.bucket= aws.s3.url=
Implementing The Class For Deleting And Uploading The Data Into The S3 Bucket.
First, get all the confidential details related to S3 Bucket from the application.properties file and Create AmazonS3 Reference.
@Value("${aws.s3.url}") private String endpointUrl; @Value("${aws.s3.247tut") private String bucketName; @Value("${aws.access.key.id}") private String accessKey; @Value("${aws.access.key.secret}") private String secretKey;
First of all, create a post Constructor to initializeAmazon
@PostConstruct private void initializeAmazon() { AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey); this.s3client = new AmazonS3Client(credentials); }
Now create a function for uploading the file on the S3 bucket but we also create more functions for converting the file into multipart and generating unique filename.
Create a function that will convert your file into multipart.
private File convertMultiPartToFile(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; }
Create A function that will create a unique name for each file
private String generateFileName(MultipartFile multiPart) { return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_"); }
Creates a function that will upload your file into specific S3 Folder
private void uploadFolderSpecifyTos3bucket(String fileName,String folder,File file) { s3client.putObject(new PutObjectRequest(bucketName+"/"+folder, fileName, file) .withCannedAcl(CannedAccessControlList.PublicRead)); }
Now, this is a single function that will call others the above functions internally and in the future, we will use only this function.
public String uploadFolderSpecify(MultipartFile multipartFile,String folder) { String fileUrl = ""; try { File file = convertMultiPartToFile(multipartFile); String fileName = generateFileName(multipartFile); fileUrl = endpointUrl+folder+"/"+ fileName; uploadFolderSpecifyTos3bucket(fileName, folder, file); file.delete(); } catch (Exception e) { e.printStackTrace(); } return fileUrl; }
Delete a file from the AWS S3 Bucket
public String deleteFileFromS3Bucket(String fileUrl) { ObjectListing listing = s3client.listObjects( bucketName, "247Tuts" ); List<S3ObjectSummary> summaries = listing.getObjectSummaries(); while (listing.isTruncated()) { listing = s3client.listNextBatchOfObjects (listing); summaries.addAll (listing.getObjectSummaries()); } String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); s3client.deleteObject(new DeleteObjectRequest(bucketName, fileName)); return "Successfully deleted"; }