Angular 6 – Display Image from Amazon S3 with SpringBoot RestAPI + Bootstrap 4 Example

In the tutorial, we show how to display images from Amazon S3 with Angular 6, Bootstrap 4 and SpringBoot RestAPI.

Related posts:
Amazon S3 – Upload/Download files with SpringBoot Amazon S3 application
Amazon S3 – Upload/download large files to S3 with SpringBoot Amazon S3 MultipartFile application
Amazon S3 – SpringBoot RestAPIs Upload/Download File/Image to S3

Technologies

  • Angular 6
  • Bootstrap 4
  • Java 1.8
  • Spring Boot 2.0.4.RELEASE
  • Maven 3.3.9
  • Spring Tool Suite 3.9.0.RELEASE
  • Amazon S3

Goal

We create 2 projects:

– SpringBoot project -> Get Image from Amazon S3 then Exposing a RestAPI.

Angular-6-Display-Image-Amazon-S3-Spring-Boot-Rest-API + spring-boot-project-structure

– Angular 6 project -> Display image from RestAPI

Angular-6-Display-Image-Amazon-S3-Spring-Boot-Rest-API + angular-6-project

Result:

File on Amazon S3 ->

Angular-6-Display-Image-Amazon-S3-Spring-Boot-Rest-API + file-on-amazon-s3

Display Image ->

Angular-6-Display-Image-Amazon-S3-Spring-Boot-Rest-API + file-on-amazon-s3

Practice

Angular 6 Client
Setup Angular project

We create Angular6DisplayImage project:

Angular-6-Display-Image-Amazon-S3-Spring-Boot-Rest-API + install-angular-project

Then install Bootstrap by commandline:

>npm install bootstrap jquery --save

Configure installed Bootstrap & JQuery in angular.json file:

...
 
"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
  "node_modules/jquery/dist/jquery.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
]
 
...
Display Image Component

We create a display-image component by commandline ng generate component DisplayImage.

Implement style display-image.component.html:

Angular Display Images


Grokonez-About Image Grokonez-About Image

Implement class display-image.component.ts ->

import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-display-image',
  templateUrl: './display-image.component.html'
})
export class DisplayImageComponent implements OnInit {
 
  constructor() { }
 
  ngOnInit() {
  }
 
}

Add app-display-image seletor to app.component.html:


SpringBoot Server
Create SpringBoot project

We use SpringToolSuite to create a SpringBoot project with dependency:


	org.springframework.boot
	spring-boot-starter-web


    com.amazonaws
    aws-java-sdk
    1.11.379

Configure Amazon S3 Client

S3Config.java ->

package com.ozenero.displayimage.s3;

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;
	}
}

Add Amazon S3 configuration in application.properties file:

gkz.aws.access_key_id=AKIAIFI4GW5D4TLCTZBA
gkz.aws.secret_access_key=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
gkz.s3.bucket=ozenero-s3-bucket
gkz.s3.region=us-east-2
Implement Download Image from S3

Create interface S3Services.java ->

package com.ozenero.displayimage.service;

import java.io.ByteArrayOutputStream;

public interface S3Services {
	public ByteArrayOutputStream downloadFile(String keyName);
}

Implement S3ServicesImpl.java ->

package com.ozenero.displayimage.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

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 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.S3Object;
import com.ozenero.displayimage.service.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;
	}
}

Expose Image RestAPI

DownloadFileController ->

package com.ozenero.displayimage.controller;

import java.io.ByteArrayOutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ozenero.displayimage.service.S3Services;


@RestController
public class DownloadFileController {
 	
	@Autowired
	S3Services s3Services;
	 	
    /*
     * Download Files
     */
	@GetMapping("/api/image/logo")
	public ResponseEntity downloadFile() {
		String keyname = "ozenero-logo.png";
		ByteArrayOutputStream downloadInputStream = s3Services.downloadFile(keyname);
	
		return ResponseEntity.ok()
					.contentType(MediaType.IMAGE_PNG)
					.header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + keyname + "\"")
					.body(downloadInputStream.toByteArray());	
	}
}
Run & Check Results

– Build & Run SpringBoot project with commandlines {mvn clean install, mvn spring-boot:run}.
– Run the Angular project as commandline: ng serve

Upload File to Amazon S3 ->

Angular-6-Display-Image-Amazon-S3-Spring-Boot-Rest-API + file-on-amazon-s3

Display Image ->

Angular-6-Display-Image-Amazon-S3-Spring-Boot-Rest-API + results

SourceCode

Angular6DisplayImage
SpringBootImageRestAPI

Note: In SpringBootImageRestAPI project, open application.properties file, then change gkz.aws.access_key_id & gkz.aws.secret_access_key to yours.

Leave a Reply

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