Uploading files and images to AWS S3 Bucket using java in Spring Boot Application

1. Create AWS account

You can create it here

After creating AWS account you are getting accessKey and secretKey.

 

2. Create S3 bucket

Create S3 bucket name.

 

3. Create Spring Boot project

Add amazon Maven dependency in pom file.

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

 

4 . application.yml file

Add all add s3 bucket details like bucket name, base url, accessKey and secretKey.


aws.accessKey=XXXXXXXXXXX aws.secretKey=XXXXXXXXXXXXXXXXXXXXXXXX aws.s3bucket.name=vaadin-upload bucketName: XXXXXXXXX baseUrl: https://s3-ap-east-5.amazonaws.com

 

5.  Creating RestController for image upload

In this controller we are creating a post method where we pass image file MultipartFile and passing user id for uploading image for that user .



package com.technicalRound.web.rest; import com.technicalRound.service.UserService; import io.github.jhipster.web.util.HeaderUtil; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/api") public class UserResource { private final Logger log = LoggerFactory.getLogger(UserResource.class); private static final String ENTITY_NAME = "user"; private final UserService userService; public UserResource(UserService userService) { this.userService = userService; } @PutMapping("/user/image/{id}") public ResponseEntity<String> userImageUpload( @RequestPart(value = "image") MultipartFile image, @PathVariable Long id) throws URISyntaxException, IOException { userService.saveImage(image, id); return ResponseEntity.ok() .headers( HeaderUtil.createEntityUpdateAlert( "applicationName", false, ENTITY_NAME, id.toString())) .body("Upload Successfully"); } }

 

6. Creating serviceImpl

In this UserServiceImpl class we are first deleting previous image and then upload new image . Calling a method uplaodFile from FileUploadUtil class and passing value image , image folder name where we store this image in AWS S3 bucket and passing user name for unique file name.



package com.technicalRound.service.impl; import com.technicalRound.config.FileUploadUtil; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @Service @Transactional public class UserServiceImpl{ private final Logger log = LoggerFactory.getLogger(UserServiceImpl.class); private FileUploadUtil fileUploadUtil; @Value("${image.folder.userImageFolder}") private String userImageFolder; public UserServiceImpl( FileUploadUtil fileUploadUtil) { this.fileUploadUtil = fileUploadUtil; } @Override public void saveImage(MultipartFile image, Long id) { log.debug("Image save for User using id : {}", id); Optional<User> userInfo = userRepository.findById(id); if (userInfo.isPresent()) { User user = userInfo.get(); fileUploadUtil.deleteFileFromS3bucket(userImageFolder, user.getUserImage()); fileUploadUtil.uplaodFile( user.getName().replaceAll(Constants.DOUBLESLASH, Constants.DOUBLEQUOTE), userImageFolder, image)); } } }

 

7 Creating FileUploadUtil class for file or image uplad method

In this class we are uploading file in S3 bucket, first converting MultiPartFile to File and than creating unique file Name for storing in S3 bucket After these all process we are upload file to S3 bucket.

 

package com.technicalRound.config;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FileUploadUtil {

  @Autowired private AmazonS3 amazonS3Client;

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

  public String uplaodFile(
      final String imageName, final String type, final MultipartFile multipartFile) {
    File file = convertMultiPartFileToFile(multipartFile);
    String uniqueFileName = generateFileName(imageName, multipartFile.getOriginalFilename());

    uploadFileToS3bucket(type + Constants.SLASH + uniqueFileName, file, bucketName);
    file.delete();

    return uniqueFileName;
  }

  private File convertMultiPartFileToFile(final MultipartFile file) {
    File convertedFile = new File(file.getOriginalFilename());
    try (FileOutputStream fos = new FileOutputStream(convertedFile)) {
      fos.write(file.getBytes());
    } catch (IOException e) {
    }
    return convertedFile;
  }

  private String generateFileName(final String imageName, final String fileName) {
    StringBuilder uniqueFileName = new StringBuilder(imageName);
    uniqueFileName.append(Constants.UNDERSCORE).append(System.currentTimeMillis()).append(Constants.UNDERSCORE).append(fileName);
    return uniqueFileName.toString();
  }

  private void uploadFileToS3bucket(
      final String fileName, final File file, final String bucketName) {
    amazonS3Client.putObject(new PutObjectRequest(bucketName, fileName, file));
  }

  public void deleteFileFromS3bucket(final String type, final String fileName) {
    amazonS3Client.deleteObject(bucketName, type + Constants.SLASH + fileName);
  }
}

 

Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.

One Reply on “Uploading files and images to AWS S3 Bucket using java in Spring Boot Application”

Leave a Reply

Your email address will not be published. Required fields are marked *