Angular and AWS S3: Storing and Serving Static Assets

This tutorial will guide you through the process of storing and serving static assets in Angular using AWS S3. Angular is a popular JavaScript framework for building web applications, while AWS S3 is a cloud storage service provided by Amazon Web Services. By leveraging the power of AWS S3, you can easily store and serve your static assets, such as images, stylesheets, and JavaScript files, in a scalable and cost-effective manner.

angular aws s3 storing serving static assets

Introduction

What is Angular?

Angular is a powerful JavaScript framework for building web applications. It provides a structured approach to web development by utilizing declarative templates, dependency injection, and modular architecture. With Angular, you can easily create dynamic and responsive user interfaces, handle data binding, and implement client-side routing.

What is AWS S3?

AWS S3 (Simple Storage Service) is a cloud storage service provided by Amazon Web Services. It allows you to store and retrieve any amount of data from anywhere on the web. S3 is highly scalable, durable, and secure, making it an ideal choice for storing static assets for your Angular applications.

Setting Up AWS S3

Before we can start using AWS S3 to store and serve our static assets, we need to set up an S3 bucket and configure its permissions.

Creating an AWS S3 Bucket

To create an S3 bucket, follow these steps:

  1. Sign in to the AWS Management Console and open the S3 console.
  2. Click on the "Create bucket" button.
  3. Enter a unique name for your bucket and choose a region.
  4. Leave the default settings for bucket properties and permissions.
  5. Click on the "Create bucket" button to create your S3 bucket.

Configuring Bucket Permissions

To configure the permissions for your S3 bucket, follow these steps:

  1. Open the S3 console and navigate to your bucket.
  2. Click on the "Permissions" tab.
  3. Under the "Bucket policy" section, click on the "Edit" button.
  4. In the bucket policy editor, enter the following policy to allow public read access to your static assets:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PublicReadGetObject",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::your-bucket-name/*"
    }
  ]
}
  1. Replace "your-bucket-name" with the name of your bucket.
  2. Click on the "Save" button to save the bucket policy.

Uploading Static Assets

To upload your static assets to the S3 bucket, follow these steps:

  1. Open the S3 console and navigate to your bucket.
  2. Click on the "Upload" button.
  3. Drag and drop your static assets into the file upload area, or click on the "Add files" button to select them from your local machine.
  4. Click on the "Next" button to proceed.
  5. Leave the default settings for permissions and metadata.
  6. Click on the "Next" button to review your upload.
  7. Click on the "Upload" button to start the upload process.

Integrating Angular with AWS S3

To integrate Angular with AWS S3, we need to install the AWS SDK for JavaScript and configure our AWS credentials.

Installing AWS SDK for JavaScript

To install the AWS SDK for JavaScript, run the following command in your Angular project directory:

npm install aws-sdk

This will install the AWS SDK as a dependency in your project.

Configuring AWS Credentials

To configure your AWS credentials, follow these steps:

  1. Open the AWS Management Console and navigate to the IAM console.
  2. Click on the "Users" link in the left navigation panel.
  3. Click on your username to open the user details page.
  4. Click on the "Security credentials" tab.
  5. Under the "Access keys" section, click on the "Create access key" button.
  6. Copy the access key ID and secret access key.

In your Angular project, create a new file named aws-config.ts and add the following code:

export const awsConfig = {
  region: 'your-region',
  accessKeyId: 'your-access-key-id',
  secretAccessKey: 'your-secret-access-key',
};

Replace "your-region", "your-access-key-id", and "your-secret-access-key" with your actual AWS region, access key ID, and secret access key.

Implementing File Upload in Angular

To implement file upload in Angular, we need to create a service that interacts with AWS S3. Create a new file named s3.service.ts and add the following code:

import { Injectable } from '@angular/core';
import { awsConfig } from './aws-config';
import { S3 } from 'aws-sdk';

@Injectable({
  providedIn: 'root',
})
export class S3Service {
  private s3: S3;

  constructor() {
    this.s3 = new S3(awsConfig);
  }

  uploadFile(file: File, key: string): Promise<void> {
    const params: S3.Types.PutObjectRequest = {
      Body: file,
      Bucket: 'your-bucket-name',
      Key: key,
      ACL: 'public-read',
    };

    return new Promise((resolve, reject) => {
      this.s3.putObject(params, (error) => {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      });
    });
  }
}

Replace "your-bucket-name" with the name of your S3 bucket.

To use the S3Service in your Angular component, import it and inject it into the component's constructor:

import { Component } from '@angular/core';
import { S3Service } from './s3.service';

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.css'],
})
export class UploadComponent {
  constructor(private s3Service: S3Service) {}

  onFileSelected(event: Event): void {
    const file = (event.target as HTMLInputElement).files[0];
    const key = 'path/to/your/file.jpg';

    this.s3Service.uploadFile(file, key)
      .then(() => {
        console.log('File uploaded successfully');
      })
      .catch((error) => {
        console.error('Failed to upload file:', error);
      });
  }
}

In the above example, we have an UploadComponent that handles file selection and uploads the selected file to AWS S3 using the S3Service.