DEV Community

loading...

Angular 11 Amazon S3 HttpClient + SpringBoot - Upload/Download Files/Images Example

loizenai profile image loizenai ・5 min read

https://grokonez.com/angular-11-amazon-s3-springboot-upload-download

Tutorial: Angular 11 Amazon S3 HttpClient + SpringBoot - Upload/Download Files/Images Example

Amazon Simple Storage Service (Amazon S3) is object storage built to store and retrieve any amount of data from web or mobile. Amazon S3 is designed to scale computing easier for developers. In the tutorial, we show how to build an Angular 11 App Client to upload/download files/images to/from Amazon S3 with Spring Boot RestApi Server.

Related posts:
Amazon S3 – SpringBoot RestAPIs Upload/Download File/Image to S3
Amazon S3 – SpringBoot RestAPIs List All Files in S3 Bucket

Technologies

– Angular 11
– Java 1.8
– Spring Boot 2.0.4.RELEASE
– Maven 3.3.9
– Spring Tool Suite 3.9.0.RELEASE

  • Amazon S3

    Demo

    Overview

    Spring Boot Server

    We expose 3 RestAPIs:
  • @PostMapping("/api/file/upload")
  • @GetMapping("/api/file/{keyname}")
  • @GetMapping("/api/file/all")

angular-6-spring-boot-amazon-s3-upload-download-files + springboot project

– For init an AmazonS3 client, we use:


BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsId, awsKey);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
            .withRegion(Regions.fromName(region))
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .build();
– For upload S3 objects, we use:

public PutObjectResult putObject(
            String bucketName, String key, InputStream input, ObjectMetadata metadata)
            throws SdkClientException, AmazonServiceException;
– For download S3 objects, we use:

public S3Object getObject(GetObjectRequest getObjectRequest)
            throws SdkClientException, AmazonServiceException;

Angular 11 App Client

angular-6-spring-boot-amazon-s3-upload-download-files + angular projectupload-file.service provides methods: push File to Storage and get Files. – list-upload.component gets and displays list of Files. – form-upload.component helps upload File. – details-upload.component is detail for each item in list of Files angular-6-spring-boot-amazon-s3-upload-download-files + angular-component-overview

Practice

SpringBoot Server

Create SprigBoot Project

We use SpringToolSuite to create SpringBoot project with needed dependencies:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.11.379</version>
</dependency>

Configure Amazon Client

S3Config.java ->

package com.grokonez.s3.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
 
@Configuration
public class S3Config {
    @Value("${gkz.aws.access_key_id}")
    private String awsId;
 
    @Value("${gkz.aws.secret_access_key}")
    private String awsKey;
    
    @Value("${gkz.s3.region}")
    private String region;

    @Bean
    public AmazonS3 s3client() {
        
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsId, awsKey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                                .withRegion(Regions.fromName(region))
                                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                                .build();
        
        return s3Client;
    }
}
In application.properties, add aws configuration:
gkz.aws.access_key_id=// change to your access_key_id
gkz.aws.secret_access_key=// change to your secret_access_key
gkz.s3.bucket=grokonez-s3-bucket
gkz.s3.region=us-east-2

S3 Upload/Download Service

Interface S3Services.java ->


package com.grokonez.s3.services;

import java.io.ByteArrayOutputStream;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

public interface S3Services {
    public ByteArrayOutputStream downloadFile(String keyName);
    public void uploadFile(String keyName, MultipartFile file);
    public List listFiles();
}

Implementation S3ServicesImpl.java ->


package com.grokonez.s3.services.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.grokonez.s3.services.S3Services;
 
@Service
public class S3ServicesImpl implements S3Services {
    
    private Logger logger = LoggerFactory.getLogger(S3ServicesImpl.class);
    
    @Autowired
    private AmazonS3 s3client;
 
    @Value("${gkz.s3.bucket}")
    private String bucketName;
 
    @Override
    public ByteArrayOutputStream downloadFile(String keyName) {
        try {
            S3Object s3object = s3client.getObject(new GetObjectRequest(bucketName, keyName));
            
            InputStream is = s3object.getObjectContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[4096];
            while ((len = is.read(buffer, 0, buffer.length)) != -1) {
                baos.write(buffer, 0, len);
            }
            
            return baos;
        } catch (IOException ioe) {
            logger.error("IOException: " + ioe.getMessage());
        } catch (AmazonServiceException ase) {
            logger.info("sCaught an AmazonServiceException from GET requests, rejected reasons:");
            logger.info("Error Message:    " + ase.getMessage());
            logger.info("HTTP Status Code: " + ase.getStatusCode());
            logger.info("AWS Error Code:   " + ase.getErrorCode());
            logger.info("Error Type:       " + ase.getErrorType());
            logger.info("Request ID:       " + ase.getRequestId());
            throw ase;
        } catch (AmazonClientException ace) {
            logger.info("Caught an AmazonClientException: ");
            logger.info("Error Message: " + ace.getMessage());
            throw ace;
        }
        
        return null;
    }
 
    @Override
    public void uploadFile(String keyName, MultipartFile file) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            s3client.putObject(bucketName, keyName, file.getInputStream(), metadata);
        } catch(IOException ioe) {
            logger.error("IOException: " + ioe.getMessage());
        } catch (AmazonServiceException ase) {
            logger.info("Caught an AmazonServiceException from PUT requests, rejected reasons:");
            logger.info("Error Message:    " + ase.getMessage());
            logger.info("HTTP Status Code: " + ase.getStatusCode());
            logger.info("AWS Error Code:   " + ase.getErrorCode());
            logger.info("Error Type:       " + ase.getErrorType());
            logger.info("Request ID:       " + ase.getRequestId());
            throw ase;
        } catch (AmazonClientException ace) {
            logger.info("Caught an AmazonClientException: ");
            logger.info("Error Message: " + ace.getMessage());
            throw ace;
        }
    }
    
    public List listFiles() {
        
      ListObjectsRequest listObjectsRequest = 
              new ListObjectsRequest()
                    .withBucketName(bucketName);
                    //.withPrefix("test" + "/");
        
        List keys = new ArrayList<>();
        
        ObjectListing objects = s3client.listObjects(listObjectsRequest);
        
        while (true) {
            List summaries = objects.getObjectSummaries();
            if (summaries.size() < 1) {
                break;
            }
            
            for (S3ObjectSummary item : summaries) {
                if (!item.getKey().endsWith("/"))
                    keys.add(item.getKey());
            }
            
            objects = s3client.listNextBatchOfObjects(objects);
        }
        
        return keys;
    }
}

https://grokonez.com/angular-11-amazon-s3-springboot-upload-download

Discussion (0)

pic
Editor guide