Instructions for installing Amazon Simple Storage Service (S3) in Spring Boot
1. What is Amazon S3?
Amazon S3 is an object storage service built to store and retrieve data in any volume from anywhere on the Internet. This is a simple storage service that provides data storage infrastructure with extremely high durability, high availability and extremely flexible scale with very low cost.
2. Create S3 bucket
You access the following link to proceed to create the bucket
https://s3.console.aws.amazon.com/s3/home?region=us-west-2
Click create bucket
Enter the bucket and region names then select the config settings in the steps to complete the bucket creation
3. Install the environment before the code
To install the code in the project we need the following properties:
a. If running in a normal server environment or on your local machine:
1 2 3 4 5 | accessKey secretKey region bucketName |
b. If running in aws environment like EC2:
1 2 3 | region bucketName |
In this article I will guide you to run in the local environment to conduct tests offline.
Step 1: Get accessKey and secretKey
You go to My Security Credential
And proceed to create as usual. The result is an exported .csv file
Step 2: Install AWS Command Line Interface (CLI)
Link: https://aws.amazon.com/en/cli/
Like my computer is windows 64bit. I will download an .msi file and install it as usual
After installation, just with an aws –version command, you will check if you have installed it.
Step 3: Add secret key, access key, region, output format to aws configure
Go to Command Prompt, type aws configure command
And proceed to fill out the information
To view the region. You can see the list define here https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html
What about the output format. I choose to be json
4. Install the code in spring boot
Step 1:
Create a Spring Boot demo project
Step 2: Add the SDK
1 2 3 4 5 6 | <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk</artifactId> <version>1.11.163</version> </dependency> |
* ) The code file
Demo project structure:
* ) Files
a. application.yml
1 2 3 4 5 | amazonProperties: region: us-west-2 s3: bucketName: gc-demo-bucket |
b. DemoApplication
1 2 3 4 5 6 7 8 9 | @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } |
c. StorageService
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | @Service public class StorageService { private static final String JPG_EXTEND_FILE = ".jpg"; public static String CONTENT_TYPE_IMAGE = "image/jpg"; public static String IMAGE_URL_PATH_RESOURCE = "medias/images/"; //Path follow path controller -> using constants public static CharSequence CONDITION_IS_IMAGE = "image/"; private AmazonS3 s3client; @Value("${amazonProperties.region}") private String region; @Value("${amazonProperties.s3.bucketName}") private String bucketName; @PostConstruct private void initializeAmazon() { this.s3client = AmazonS3ClientBuilder .standard() .withRegion(Regions.fromName(region)) .build(); } public String saveFile(MultipartFile multipartFile) { String fileName = Generators.timeBasedGenerator().generate().toString() + JPG_EXTEND_FILE; String filePathS3 = IMAGE_URL_PATH_RESOURCE + fileName; try { InputStream inputStream = multipartFile.getInputStream(); byte[] contents = IOUtils.toByteArray(inputStream); InputStream stream = new ByteArrayInputStream(contents); ObjectMetadata meta = new ObjectMetadata(); meta.setContentLength(contents.length); meta.setContentType(CONTENT_TYPE_IMAGE); s3client.putObject(new PutObjectRequest( bucketName, filePathS3, stream, meta) .withCannedAcl(CannedAccessControlList.BucketOwnerFullControl)); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } return filePathS3; } public byte[] getImage(String nameImage) { try { S3Object s3object = s3client.getObject(bucketName, IMAGE_URL_PATH_RESOURCE + nameImage); S3ObjectInputStream inputStream = s3object.getObjectContent(); return IOUtils.toByteArray(inputStream); } catch (IOException e) { e.printStackTrace(); } return null; } } |
d. MediaController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @RestController public class MediaController { @Autowired private StorageService storageService; @PostMapping("/upload-image") public ResponseEntity uploadImage(@RequestParam("file") MultipartFile file) { return ResponseEntity.ok(storageService.saveFile(file)); } @GetMapping("/images/{name_image}") public ResponseEntity<byte[]> getImage(@PathVariable("name_image") String nameImage) { return ResponseEntity.ok() .contentType(MediaType.valueOf(StorageService.CONTENT_TYPE_IMAGE)) .body(storageService.getImage(nameImage)); } } |
* ) Postman run results
Call API upload image
Call API get image