File Upload and Download API's with Spring boot and AWS S3

Photo by Mike from Pexels
In this blog post, let's see how we can use AWS S3 as a storage to upload and download files from a spring boot application via API's.
You need to have a private S3 bucket in AWS, In my scenario my bucket name is rkdevlog
By default you will get a private bucket created for you anyway, unless you tick out Block public access. 

Since we are dealing with AWS services you need to set up AWS credentials and use them in your application. Please follow my previous blog post to configure the credentials. (Check out the points 2, 3 and attach the AmazonS3FullAccess policy)

Let's check out the code now, You can have the source code at the end of the blog post. 

S3Configuration class
Just like in our previous blog posts on aws sdk we just need to create a bean to initialized the S3 client.  One important point here is if you created a bucket in a another region which your AWS account not belong to, when building the client you just need to pass the region, for example
S3FileService class
Here, the important things to notice is the bucket Name is returning from the config file, in our case from application.yml.

Also if the requested download file is not found the the s3 bucket, then we have thrown a NoSuchFileException exception and this exception is handled in the controller class.

S3Controller class
Test the application
1) Upload a file.
Now my S3 bucket is empty, let's upload a image file. If the upload is success you will get the 200  response with the image name you set as the fileName in the form-data.

Navigate to your S3 bucket and you will the your uploaded files

2) Download a file.
Let's download the image file we uploaded. 
  • Since we have developed an API, the API is returning a byte stream for binary format file types, so to get the file from postman you need to click the send and download option. 
  • The client using this API needs to write a method to extract the byte stream and convert that to a file.
  • If the file is not found in the bucket you will receive a response status 404.
That's pretty much it with the code, you can use the example to get started with your requirement, source code can be found in the below link. Thank you very much for reading.

References & Useful Readings.