DEV Community

Cover image for Upload Operation in AWS S3 Bucket using SpringBoot REST API
Shashank Trivedi
Shashank Trivedi

Posted on

Upload Operation in AWS S3 Bucket using SpringBoot REST API

Table of Contents

Steps Follows on AWS

  • Account Creation
  • Amazon S3 Bucket Creation
  • Access Key Creation

Steps Follows on SpringBoot

  • SpringBoot Project Creation
  • Add AWS Dependency
  • Metthod Creation
  • Check the API

First Step Create Account in AWS

1.) Go to AWS Free tier section

Image description

2.) Account created Sucessfully Message

Image description

3.) Go the AWS Management console section

Image description

4.) Search S3 bucket on aws management panel

Image description

5.) Create bucket

Image description
6.) write unique name of the bucket and then click to create

Image description

7.) After created the bucket go to the security credentials

Image description

8.) Create Access Key

Image description

9.) Copy Access key And Screet in Notepad

Image description

Second Step for the SpringBoot

1.) Generate SpringBoot project using Spring Initializer

Image description

2.) Extract the zip file and Open the project in IntelijIDEA

Image description

3.) Create Controller and Service package inside the main package and create the BucketController and BucketService class

Image description

4.) Write some details on application.properties file

Image description

5.) import the aws core dependency
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.486</version>
</dependency>

Image description

6.) Create the AWS Config class inside the Configuration package


package com.shashank.bucketProject.configuration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
    @Configuration
    public class AWSConfig {
        @Value("${access-key}")
        private String accessKey;

        @Value("${secret-key}")
        private String accessSecret;
        @Value("${region}")
        private String region;

        @Bean
        public AmazonS3 s3Client() {
            AWSCredentials credentials = new BasicAWSCredentials(accessKey, accessSecret);
            System.out.println("Hello AWS");
            return AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withRegion(region).build();
        }
    }
Enter fullscreen mode Exit fullscreen mode

Image description

7.) write some code in BucketService class

package com.shashank.bucketProject.service;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 @Service
    public class BucketService {
        @Value("${bucket-name}")
        private String bucketName;
        @Autowired
        private AmazonS3 amazonS3;

        public String uploadFile(MultipartFile file) {
            File fileObj = convertMultiPartFileToFile(file);
            String fileName =  file.getOriginalFilename();
            amazonS3.putObject(new PutObjectRequest(bucketName, fileName, fileObj));
            fileObj.delete();
            return "File uploaded : " + fileName;
        }
        private File convertMultiPartFileToFile(MultipartFile file) {
            File convertedFile = new File(file.getOriginalFilename());
            try (FileOutputStream fos = new FileOutputStream(convertedFile)) {
                fos.write(file.getBytes());
            } catch (IOException e) {
                System.out.println("Error converting multipartFile to file" + e);
            }
            return convertedFile;
        }
}



Enter fullscreen mode Exit fullscreen mode

Image description

8.) write some code in BucketController class

package com.shashank.bucketProject.controller;

import com.shashank.bucketProject.service.BucketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api")
public class BucketController {

    @Autowired
    private BucketService bucketService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam(value = "file") MultipartFile file) {
        return new ResponseEntity<>(bucketService.uploadFile(file), HttpStatus.OK);
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

9.) Before Running the project change the version of spring application 2.7.8

Image description

10.) Run the springboot Application

Image description

11.) Open the Postman and check the api is working or not

Image description

12.) Now check on the aws file is uploaded or not

Image description

Top comments (0)