• Register
294 points
3

Uploading files to AWS S3 Bucket using Spring Boot

To start with what pre requisite you will need :

 

Amazon Cloud services Account which has S3 service enabled in it.

 

For this , Creat account and Go to Services – > S3.

Then create bucket  by clicking on Create bucket button and fill the form.This will create S3 bucket and enable storage for you.

 

Let’s start Spring boot Part,

 

Add maven dependency in your project as below :

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

Then add below properties in application.properties file, which is configuration of your amazon account :
cloud.aws.stack.auto=false
cloud.aws.region.static=your AWS account region
cloud.aws.credentials.accessKey=AWS IAM user access key
cloud.aws.credentials.secretKey=AWS IAM user secret key

app.awsServices.bucketName=my-demo-s3-test


 

Let’s create a controller through we can hit Rest call and upload and delete file in Amazon S3 bucket.

 

/uploadFile” and “/deleteFile”.

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

    private AmazonClient amazonClient;

    @Autowired
    BucketController(AmazonClient amazonClient) {
        this.amazonClient = amazonClient;
    }

    @PostMapping("/uploadFile")
    public String uploadFile(@RequestPart(value = "file") MultipartFile file) {
        return this.amazonClient.uploadFile(file);
    }

    @DeleteMapping("/deleteFile")
    public String deleteFile(@RequestPart(value = "url") String fileUrl) {
        return this.amazonClient.deleteFileFromS3Bucket(fileUrl);
    }
}

 

There is nothing special in the controller, except uploadFile() method recieves MultipartFile as a RequestPart.

This code is actually broken because we don’t have AmazonClient class yet, so let’s create this class with the following fields.

 

@Service
public class AmazonClient {

    private AmazonS3 s3client;

    @Value("${amazonProperties.endpointUrl}")
    private String endpointUrl;    @Value("${amazonProperties.bucketName}")
    private String bucketName;    @Value("${amazonProperties.accessKey}")
    private String accessKey;    @Value("${amazonProperties.secretKey}")
    private String secretKey;@PostConstruct
    private void initializeAmazon() {
       AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
       this.s3client = new AmazonS3Client(credentials);
}
}

 


 

S3 bucket requires File as a input to process your file so first we will need to convert file from multi part file to File.

 

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;
}

For generating unique name every time for same file we will need to make some logic as below :

 

private String generateFileName(MultipartFile multiPart) {
    return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
}

 

Now let’s add  method which uploads files to S3 bucket.

 

private void uploadFileTos3bucket(String fileName, File file) {
    s3client.putObject(new PutObjectRequest(bucketName, fileName, file)
            .withCannedAcl(CannedAccessControlList.PublicRead));
}

 

Finally, we will combine all these methods into one general that is called from our controller. This method will save a file to S3 bucket and return fileUrl which you can store to database. For example you can attach this url to user’s model if it’s a profile image etc.

 

public String uploadFile(MultipartFile multipartFile) {

    String fileUrl = "";
    try {
        File file = convertMultiPartToFile(multipartFile);
        String fileName = generateFileName(multipartFile);
        fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
        uploadFileTos3bucket(fileName, file);
        file.delete();
    } catch (Exception e) {
       e.printStackTrace();
    }
    return fileUrl;
}

 

And let’s add deleteFile() method  for deleting file from S3 Bucket.

 

public String deleteFileFromS3Bucket(String fileUrl) {
    String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    s3client.deleteObject(new DeleteObjectRequest(bucketName + "/", fileName));
    return "Successfully deleted";
}

 

Now run your pplication and test it in postman.

URL :- localhost:8080/storage/uploadFile

and select form-data as a body part and select a file whihc you wanna upload.

Hurrray you will uploaded file in Amazon S3 bucket ..

 

You can also visit other Spring boot blogs of mine from below links :-

Bean Life cycle – https://kodlogs.com/blog/9239/spring-bean-life-cycle-and-creation-of-bean-with-bean-scope

Various Annotations – https://kodlogs.com/blog/9763/framework-annotations-%40autowire-%40component-%40configuration

Postgre CRUD – https://kodlogs.com/blog/9348/create-web-application-in-spring-boot-with-postgresql-part

Rest Api/Services – https://kodlogs.com/blog/9766/rest-apis-services-with-spring-boot


Thanks for reading . . . . . . . 

 

4 Comments

comment:

thanks
Thank you for sharing this informative and useful post.
Excellent writing! Informative article. Thanks!
Please expand on this subject. Your ability to explain things is wonderful.