Saturday, August 18, 2018

Upload File on AWS S3 Using Java

Most of us know nowadays that AWS  is used for almost everything because of its cheap price as well its availability.

AWS S3 is an online storage for storing file and images and zip, literally everything you want to put. 

Most of us have some use cases where we want to upload the image to aws s3 so that it can we used anywhere we want.

#Usercase we need to get the file or Image from UI and need to upload it to AWS S3 using java.

#Approach To Achieve it 
  • first, need to add the AWS SDK for Java 
  • Then we need to Get the client of AWS which is basically creating a connection with AWS 
  • After successfully getting the connection we will use s3 API to put the image as an object in AWS.

We first need to Add the dependency of AWS SDK in our project ( maven dependency as below )


After this, we need to have the AWS Account Access key and access_id
you can get it from

Access key file will look like below

aws_secret_access_key=<Your Secret_access_key>
Note change <Your-Access-key_id> and <Your Secret_access_key> values with your access key.

Now you need to save the access key file at a location below.

~/.aws/credentials on Linux, macOS, or Unix
C:\Users\USERNAME \.aws\credentials on Windows

Now let see the Code for the Uploading of Image /File on AWS.  (Ref : here )
 we will create one jsp file where we create upload file and call the spring controller , under the controller, you can see the file and it will store to the aws s3.

Thyemleaf Html Code

<!DOCTYPE html>
<html xmlns:th="">
<title>File Upload Example</title>
<link href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"
 rel="stylesheet" />
<script type="text/javascript" src="webjars/jquery/3.3.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script th:inline="javascript">
 var _validFileExtensions = [ ".csv", ".zip" ,".png" ];
 function Validate(oForm) {
  var arrInputs = oForm.getElementsByTagName("input");
  for (var i = 0; i < arrInputs.length; i++) {
   var oInput = arrInputs[i];
   if (oInput.type == "file") {
    var sFileName = oInput.value;
    if (sFileName.length == 0) {

     alert("Please select a file to upload");
     return false;
    if (sFileName.length > 0) {
     var blnValid = false;
     for (var j = 0; j < _validFileExtensions.length; j++) {
      var sCurExtension = _validFileExtensions[j];
      if (sFileName.substr(
        sFileName.length - sCurExtension.length,
        sCurExtension.length).toLowerCase() == sCurExtension
        .toLowerCase()) {
       blnValid = true;

     if (!blnValid) {
      alert("Invalid File Extension");
      return false;

  return true;


 <div class="container-fluid padding-0">
  <div class="row padding-0">
   <div class="col-md-4">
    <h2>File Upload Example</h2>
   <div class="col-md-4" align="right"></div>
 <nav role="navigation" id="trainingset-container-id"
  class="navbar navbar-default">
  <div class="row" style="margin-top: 10px;">
   <div class="col-md-2">
    <B>Upload File</B>
   <div class="col-md-6">
    <form method="POST" action="/upload"
     onsubmit="return Validate(this);" enctype="multipart/form-data">
     <div class="col-sm-6">

      <input type="file" name="file"  />
     <div class="col-sm-6">
      <input type="submit" class="btn btn-success btn-sm" value="Upload data" />
  <div id="messageboxid">
   <div id="uploadstatus" th:if="${message}">
    <B>Status Of Uploaded File</B>
    <h6 th:text="${message}" />
This will see like this

Now we will see the Upload Controller Code.


package com.programinjava.learn.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;

public class UploadController {
 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

  if (file.isEmpty()) {
   redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
   return "redirect:uploadStatus";
//  bucket name 
  String bucketName ="atserve-photos";
//  get it from user or change it 
  String nameOffile ="myPhoto";
//  getting aws access 
  AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new ProfileCredentialsProvider())
  boolean isBucketExist =s3Client.doesBucketExist(bucketName);
  if(!isBucketExist) {
  try {
   InputStream is = file.getInputStream();
   s3Client.putObject(new PutObjectRequest(bucketName,nameOffile,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));
   redirectAttributes.addFlashAttribute("message", "SuccessFully Uploaded On AWS S3");
  }catch(Exception e) {
  return "redirect:/uploadStatus";
 public String uploadStatus(ModelMap m) {
  return "Homepage";
 public String displayHomePageForAlarm() {
  return "Homepage";


Let see what we get on AWS S3

So this is how we can see the myPhoto is now uploaded on AWS S3.


Also, learn


Post a Comment