Uploading files and images to AWS S3 Bucket

 

In this article, we are going to discuss how to upload files and images in AWS S3 Bucket, in the spring boot application.

1. Create an AWS account

You can create an AWS account directly from, click create amazon account

After creating an AWS account you can get accessKey and secretKey. These both keys we are using when we are configuring our application in the application property or application.yml through an AWS s3 bucket.

 

2. Create an S3 bucket

We need to create an S3 bucket name on the AWS website.

 

3. Create Spring Boot project

Add amazon Maven dependency in the 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 the previous image and then upload a new image. Calling a method upload file from FileUploadUtil class and passing value image, image folder name where we store this image in AWS S3 bucket and passing user name for the 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 upload method

In this class we are uploading files in the S3 bucket, first converting MultiPartFile to File and then creating a unique fileName for storing in the S3 bucket After these all process we are upload the file to the 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);
  }
}

 

Read more topics related to java

 

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

Leave a Reply

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