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.

13 Replies to “Uploading files and images to AWS S3 Bucket using java in Spring Boot Application”

  1. I intended to compose you a bit of note in order to give many thanks again for your personal magnificent principles you’ve featured in this article. It is quite remarkably generous of people like you to give openly just what a number of us might have marketed as an e book to generate some dough for themselves, most notably given that you could possibly have done it if you ever decided. These points as well served to be a fantastic way to fully grasp other people have similar fervor much like my own to know the truth lots more pertaining to this issue. I am certain there are millions of more fun opportunities in the future for individuals who looked at your blog post.

  2. Needed to write you this very small word to help thank you very much yet again with your wonderful views you have shown on this website. This is so wonderfully open-handed with you to supply without restraint what exactly some people would have supplied for an electronic book to make some profit on their own, specifically since you might well have tried it in the event you wanted. Those tricks likewise worked to provide a great way to understand that the rest have the same zeal the same as my very own to understand whole lot more with respect to this problem. I think there are thousands of more pleasurable times up front for those who view your website.

  3. My husband and i ended up being cheerful Albert could carry out his analysis because of the ideas he acquired from your blog. It’s not at all simplistic just to always be freely giving facts a number of people could have been making money from. And now we acknowledge we’ve got the blog owner to appreciate because of that. All of the explanations you’ve made, the easy blog menu, the friendships you give support to engender – it’s got everything fantastic, and it’s really facilitating our son and the family feel that the issue is entertaining, and that is particularly indispensable. Thank you for all the pieces!

  4. I am commenting to let you know of the fantastic encounter my cousin’s daughter experienced reading your site. She even learned many issues, not to mention what it’s like to have a wonderful giving mindset to have many people quite simply grasp chosen grueling subject areas. You really exceeded our expectations. Many thanks for giving the informative, healthy, educational and as well as easy thoughts on the topic to Jane.

  5. A lot of thanks for all your efforts on this site. Gloria loves engaging in investigation and it’s easy to understand why. Most people learn all regarding the lively mode you present rewarding techniques through this web site and even inspire participation from some others on the point then our favorite princess is really starting to learn a whole lot. Take advantage of the rest of the year. You are always doing a splendid job.

  6. I enjoy you because of all of the effort on this blog. Betty delights in carrying out internet research and it’s easy to see why. A lot of people hear all about the compelling form you convey both interesting and useful guidance by means of the blog and attract contribution from other individuals about this area and my child has always been becoming educated a great deal. Enjoy the remaining portion of the new year. You’re carrying out a brilliant job.

  7. I simply wanted to thank you very much once more. I do not know what I would have tried without these techniques shared by you regarding that subject matter. It was actually an absolute scary scenario in my position, nevertheless taking note of this specialized tactic you solved the issue took me to weep with happiness. Now i’m thankful for your support and thus sincerely hope you really know what an amazing job you have been putting in training the mediocre ones via your webpage. Most probably you haven’t met any of us.

  8. I simply wanted to thank you so much once more. I do not know what I would’ve sorted out without these strategies revealed by you over that subject. It was an absolute horrifying matter in my position, nevertheless spending time with this specialized style you resolved the issue took me to leap with happiness. I will be happy for your service and then sincerely hope you realize what an amazing job you have been providing teaching some other people using your web site. Most likely you haven’t got to know any of us.

  9. Thanks for your own work on this website. My mother take interest in participating in research and it is simple to grasp why. My spouse and i notice all relating to the powerful way you provide valuable tips via your website and in addition recommend response from visitors on this subject matter while our own simple princess is undoubtedly studying so much. Take pleasure in the rest of the year. You have been performing a terrific job.

Leave a Reply

Your email address will not be published.