REST API to upload Multipart image file to AWS S3 Bucket

In this article we are going to see how to upload base64 image to AWS s3 bucket.

Dependency

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

Multipart File to File

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

Spring Boot REST Controller (StorageController)

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

  @Autowired
  StorageService storageService;

  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public String upload(@RequestParam("file") MultipartFile file,
  @RequestParam("fileName") String fileName) {
    storageService.store(file, fileName);
    return "Upload success";
  }
}
}

StorageService

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.mirthbees.stepsrank.bean.ProfileUploadBean;
import com.mirthbees.stepsrank.utility.Utils;

@Service
public class StorageService {

  Logger log = LoggerFactory.getLogger(this.getClass().getName());

  // @Autowired
  private AmazonS3 s3client;

  private static String defaultRegion = "ap-south-1";

  @Value("${amazonProperties.endpointUrl.mumbai}")
  private String defaultEndpointUrl;

  @Value("${amazonProperties.bucketName}")
  private String bucketName;

  @Value("${amazonProperties.accessKey}")
  private String accessKey;

  @Value("${amazonProperties.secretKey}")
  private String secretKey;

  public String store(MultipartFile multipartFile, String fileName) throws Exception {
  String fileUrl = "";
  try {
    File file = Utils.convertMultiPartToFile(multipartFile); // refer the above code for this method
    buildAmazonS3Client(defaultRegion, defaultEndpointUrl);
    fileUrl = defaultEndpointUrl + "/" + bucketName + "/" + fileName;
    // once the file is uploaded successfully then update the same url in the user table  
    uploadFileTos3bucket(fileName, file);
    file.delete();
    log.info("File uploaded to S3 successfully");  
  } catch (Exception e) {
    log.error("Error while uploadeding the file to S3" + e);
    // fileUrl = "exception: "+e.getMessage();
    //throw e;
    return "upload failed!";
  }
   return "upload success!");
  }

  private void uploadFileTos3bucket(String fileName, File file) {
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setCacheControl("51635000");
    metadata.setExpirationTime(Utils.getTwentyYearsFromNow());
    s3client.putObject(new PutObjectRequest(bucketName, fileName, file)
      .withCannedAcl(CannedAccessControlList.PublicRead).withMetadata(metadata));

  }

  void buildAmazonS3Client(String defaultRegion, String endpoint) {
    AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
    AmazonS3ClientBuilder amazons3ClientBuilder = AmazonS3ClientBuilder.standard()
      .withCredentials(new AWSStaticCredentialsProvider(credentials))
      .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, defaultRegion));
    this.s3client = amazons3ClientBuilder.build();
  }

}

AWS Properties

amazonProperties.endpointUrl.mumbai=https://s3.ap-south-1.amazonaws.com
amazonProperties.accessKey=YOUR_ACCESS_KEY
amazonProperties.secretKey=YOUR_SECRET_KEY
amazonProperties.bucketName=YOUR_BUCKET_NAME

getTwentyYearsFromNow (Utility for AWS Bucket File Cache)

public static Date getTwentyYearsFromNow() {
  Calendar c = Calendar.getInstance();
  c.setTime(new Date());
  c.add(Calendar.YEAR, 20);
  Date newDate = c.getTime();
  return newDate;
}

Testing & Output

REST API:

http://localhost:8712/storage/upload

Form Data:

Leave a Reply