How to Upload Files in S3 Buckets in Java/Spring Boot

In Amazon S3, files or any other data are stored as objects in buckets. A bucket is nothing but a logical container for objects in S3.

To upload files in S3, you will need to add the AWS Java SDK For Amazon S3 dependency to your application. Here is the Maven repository for Amazon S3 SDK for Java.


Gradle Dependency

Add the following dependency to the build.gradle file:


implementation group: 'com.amazonaws', name: 'aws-java-sdk-s3', version: '1.11.1009'

Maven Dependency

Add the following dependency to the pom.xml file:


    

Example Code

Here is a Java/Spring Boot example code for uploading files in Amazon S3:

Service Class

amazon-s3-sample/src/main/java/com/sample/s3/service/S3UploadExampleService.java

package com.sample.s3.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Service;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
 
@service
public class S3UploadExampleService {
 
  private String s3BaseUrl = "https://s3-us-east-1.s3.amazonaws.com/";
 
  private String bucketName = "my-test-bucket";
 
  private String folderName = "/myfolder/images/";
 
  @Autowired
  private AmazonS3 s3Client;
 
  public Map<String,String> uploadFileInS3(MultipartFile multipartfile) {
 
     Map<String,String> fileUrlMap = new HashMap<>();
 
     if(multipartfile != null && !multipartfile.isEmpty()) {
 
        String filePath = multipartfile.getOriginalFilename();
 
        File file = new File(filePath);
 
        try(FileOutputStream fos = new FileOutputStream(file)) {
 
           if(!file.exists()) {
              file.createNewFile();
           }
 
           fos.write(multipartfile.getBytes());
           fos.flush();
          
           /*uploading file to S3*/
           s3Client.putObject(new PutObjectRequest(bucketName, 
            folderName + "/" + file.getName(), file)
            .withCannedAcl(CannedAccessControlList.PublicRead));
 
           /* Url location of the uploaded file in S3*/
 
           String s3filePathUrl = s3BaseUrl.concat(bucketName)
            .concat(folderName).concat(file.getName()).replaceAll("\\s", "+");
 
           fileUrlMap.put("fileUrl",s3filePathUrl)
 
           file.delete();
 
        } catch (FileNotFoundException e) {
           e.printStackTrace();
        } catch (FileNotFoundException e) {
           e.printStackTrace();
        }
      }
    return fileUrlMap;
   }
 
}

Web Controller

amazon-s3-sample/src/main/java/com/sample/s3/controller/S3FileUploadController.java

package com.sample.s3.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
import com.example.s3.service.S3UploadExampleService;

@RestController
@RequestMapping(value = "/api/files")
public class S3FileUploadController {

  @Autowired
  private S3UploadExampleService s3UploadExampleService;

  @PostMapping(value = "/upload")
  public ResponseEntity<Map<String,String>> uploadFile(MultipartFile multipartfile) {

     return ResponseEntity.ok(s3UploadExampleService .uploadFileInS3(multipartfile));
  }

}