Angular 12 Amazon S3 example – Get list Files from S3 Bucket

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 make web-scale computing easier for developers. In previous post, we had known how to upload file to Amazon S3. This tutorial will help you create an Angular 12 App that can get list Files from Amazon S3 Bucket.

Related Post: Angular 12 Amazon S3 example – How to upload File to S3 Bucket

Reactjs Jwt SpringBoot Token Authentication Example
Spring Boot Angular 11 Pagination Example
Angular Client Side Pagination with Nodejs + MySQL
Django Angular 10 CRUD Example

I. Technology

– Angular 12
– AWS SDK

II. How to do

1. Set up Angular 12 Project integrating with AWS SDK

Create your own Angular 12 Project, then follow these steps to integrate AWS SDK.

2. Upload with pre-set Access Control List (ACL)

Amazon S3 access control lists (ACLs) enable you to manage access to buckets and objects. It defines which AWS accounts or groups are granted access and the type of access.

Amazon S3 supports a set of predefined grants, known as canned ACLs which predefined a set of grantees and permissions. Some of them are:
private: Owner gets FULL_CONTROL. No one else has access rights (default).
public-read: Owner gets FULL_CONTROL. The AllUsers group (see Who Is a Grantee?) gets READ access.
public-read-write: Owner gets FULL_CONTROL. The AllUsers group gets READ and WRITE access. Granting this on a bucket is generally not recommended.
authenticated-read: Owner gets FULL_CONTROL. The AuthenticatedUsers group gets READ access.
– …

In this example, we use public-read:

uploadfile(file) {
  const params = {
    Bucket: 'BUCKET',
    Key: 'FOLDER/' + file.name,
    Body: file,
    ACL: 'public-read'
  };

  this.getS3Bucket().upload(params, function (err, data) {
    // ...
  });
}

It will help us can directly download file from url.

3. Get list Files

Use listObjects() method to get list files from bucket, files array will be in data.Contents:

const params = {
  Bucket: 'BUCKET',
  Prefix: 'FOLDER'
};

this.getS3Bucket().listObjects(params, function (err, data) {
  if (err) {
    console.log('There was an error getting your files: ' + err);
    return;
  }

  // data.Contents
});

4. Display list Files

To display them, we will work with Observable object:
– Upload Service to work with S3 Bucket:

// ------- upload-service -------
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

getFiles(): Observable> {
  const fileUploads = new Array();
  // ...

  this.getS3Bucket().listObjects(params, function (err, data) {
    
    const fileDatas = data.Contents;

    fileDatas.forEach(function (file) {
      // fileUploads appends file...
    });
  });

  return Observable.of(fileUploads);
}

– Display list files component:

// ------- display-component -------
fileUploads: Observable>;
// ...

showFiles(enable: boolean) {
  // ...
  this.fileUploads = this.uploadService.getFiles();
}

– HTML component with ngFor and async:

<div *ngFor="let file of fileUploads | async">
	<div class="panel-body">
		<app-details-upload [fileUpload]='file'></app-details-upload>
	</div>
</div>

III. Practice

1. Project Overview

1.1 Goal

We will build an Angular 12 Firebase App that can:
– helps user choose file from local and upload it to Amazon S3 Bucket
– display list files from Amazon S3 Bucket

amazon-s3-angular4-get-list-files-goal

1.2 Structure

amazon-s3-angular4-get-list-files-structure

2. Step by step

2.1 Set up Angular 12 Project integrating with AWS SDK

Create your own Angular 12 Project, then follow these steps to integrate AWS SDK.

2.2 Setup @NgModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormUploadComponent } from './form-upload/form-upload.component';
import { UploadFileService } from './upload-file.service';
import { DetailsUploadComponent } from './details-upload/details-upload.component';
import { ListUploadComponent } from './list-upload/list-upload.component';

@NgModule({
  declarations: [
    AppComponent,
    FormUploadComponent,
    DetailsUploadComponent,
    ListUploadComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [UploadFileService],
  bootstrap: [AppComponent]
})
export class AppModule { }

2.3 Model Class

export class FileUpload {
    name: string;
    url: string;

    constructor(name: string, url: string) {
        this.name = name;
        this.url = url;
    }
}

2.4 Upload Service

import { Injectable } from '@angular/core';
import * as AWS from 'aws-sdk/global';
import * as S3 from 'aws-sdk/clients/s3';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { FileUpload } from './file-upload';

@Injectable()
export class UploadFileService {

  FOLDER = 'jsa-s3/';
  BUCKET = 'jsa-angular4-bucket';

  constructor() { }

  private getS3Bucket(): any {
    const bucket = new S3(
      {
        accessKeyId: 'ACCESS-KEY-ID',
        secretAccessKey: 'SECRET-ACCESS-KEY',
        region: 'us-east-1'
      }
    );

    return bucket;
  }

  uploadfile(file) {
    const params = {
      Bucket: this.BUCKET,
      Key: this.FOLDER + file.name,
      Body: file,
      ACL: 'public-read'
    };

    this.getS3Bucket().upload(params, function (err, data) {
      if (err) {
        console.log('There was an error uploading your file: ', err);
        return false;
      }

      console.log('Successfully uploaded file.', data);
      return true;
    });
  }

  getFiles(): Observable> {
    const fileUploads = new Array();

    const params = {
      Bucket: this.BUCKET,
      Prefix: this.FOLDER
    };

    this.getS3Bucket().listObjects(params, function (err, data) {
      if (err) {
        console.log('There was an error getting your files: ' + err);
        return;
      }

      console.log('Successfully get files.', data);

      const fileDatas = data.Contents;

      fileDatas.forEach(function (file) {
        fileUploads.push(new FileUpload(file.Key, 'https://s3.amazonaws.com/' + params.Bucket + '/' + file.Key));
      });
    });

    return Observable.of(fileUploads);
  }

}

2.5 Form Upload Compoment

import { Component, OnInit } from '@angular/core';
import { UploadFileService } from '../upload-file.service';

@Component({
  selector: 'app-form-upload',
  templateUrl: './form-upload.component.html',
  styleUrls: ['./form-upload.component.css']
})
export class FormUploadComponent implements OnInit {

  selectedFiles: FileList;

  constructor(private uploadService: UploadFileService) { }

  ngOnInit() {
  }

  upload() {
    const file = this.selectedFiles.item(0);
    this.uploadService.uploadfile(file);
  }

  selectFile(event) {
    this.selectedFiles = event.target.files;
  }
}

form-upload.component.html:

<label class="btn btn-default">
  <input type="file" (change)="selectFile($event)">
</label>

<button class="btn btn-success" [disabled]="!selectedFiles" (click)="upload()">Upload</button>

2.6 DetailsUpload Component

details-upload.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { FileUpload } from '../file-upload';

@Component({
  selector: 'app-details-upload',
  templateUrl: './details-upload.component.html',
  styleUrls: ['./details-upload.component.css']
})
export class DetailsUploadComponent implements OnInit {

  @Input() fileUpload: FileUpload;

  constructor() { }

  ngOnInit() {
  }

}

details-upload.component.html

<a href="{{fileUpload.url}}">{{fileUpload.name}}</a>

2.7 ListUpload Component

list-upload.component.ts

import { Component, OnInit } from '@angular/core';
import { UploadFileService } from '../upload-file.service';
import { Observable } from 'rxjs/Observable';
import { FileUpload } from '../file-upload';

@Component({
  selector: 'app-list-upload',
  templateUrl: './list-upload.component.html',
  styleUrls: ['./list-upload.component.css']
})
export class ListUploadComponent implements OnInit {

  showFile = false;
  fileUploads: Observable>;

  constructor(private uploadService: UploadFileService) { }

  ngOnInit() {
  }

  showFiles(enable: boolean) {
    this.showFile = enable;

    if (enable) {
      this.fileUploads = this.uploadService.getFiles();
    }
  }

}

list-upload.component.html

<button class="button btn-info" *ngIf='showFile'
	(click)='showFiles(false)'>Hide Files</button>
 
<button class="button btn-info" *ngIf='!showFile'
	(click)='showFiles(true)'>Show Files</button>
 
<div [hidden]="!showFile">
	<div class="panel panel-primary">
		<div class="panel-heading">List of Files</div>
		<div *ngFor="let file of fileUploads | async">
			<div class="panel-body">
				<app-details-upload [fileUpload]='file'></app-details-upload>
			</div>
		</div>
	</div>
</div>

2.8 App Component

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'JavaSampleApproach';
  description = 'Angular4-AmazonS3 Demo';
}

app.component.html

<div class="container" style="max-width: 400px">
	<div style="color: blue; margin-bottom: 20px">
		<h1>{{title}}</h1>
		<h3>{{description}}</h3>
	</div>
 
	<app-form-upload></app-form-upload>

	<br/>
	<br/>
	
	<app-list-upload></app-list-upload>
</div>

2.9 Check Result

Run the App, go to http://localhost:4200/.

– Upload files, then click on Show Files button:
amazon-s3-angular4-get-list-files-result

– S3 Bucket https://console.aws.amazon.com/s3/buckets/jsa-angular4-bucket/jsa-s3:
amazon-s3-angular4-result-bucket

IV. Source Code

Angular4AmazonS3-get-list-files

0 0 votes
Article Rating
Subscribe
Notify of
guest
245 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments