<!DOCTYPE html>
<html>
  <head>
    <!-- Set the base href -->
    <script>document.write('<base href="' + document.location + '" />');</script>
    <title>Angular S3 Upload</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfills -->
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>

    <script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
    <script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
    
    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.js')
            .catch(function(err){ console.error(err); });
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
  </head>

  <body>
    <app-root>loading...</app-root>
  </body>

</html>


<!-- 
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
/* Styles go here */

/**
 * WEB ANGULAR VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      // Copy of compiler options in standard tsconfig.json
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      // paths serve as alias
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs@5.0.1',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'ts':                        'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript':                'npm:typescript@2.0.10/lib/typescript.js',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });

})(this);
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);


/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
import { Component } from '@angular/core';
import {Http} from "@angular/http";

declare var CryptoJS: any;

@Component({
  selector: 'app-root',
  template: `
  <input type="text" [(ngModel)]="config.bucket" placeholder="The S3 Bucket"/><br/>
  <input type="text" [(ngModel)]="config.accessKey" placeholder="Your Access Key"/><br/>
  <input type="text" [(ngModel)]="config.secretAccessKey" placeholder="Your Secret Access Key"/><br/>
  <input type="text" [(ngModel)]="config.region" placeholder="The Region of the Bucket"/><br/>
  <input type="file" (change)="upload($event)"/><br/>
  <img *ngIf="imagePath" [src]="imagePath">
  `
})
export class AppComponent {
  uploader: S3Uploader;
  imagePath: string;
  config = new S3Config();
  
  constructor(private http: Http) {
    this.uploader = new S3Uploader();
    
    // Input your S3 Config
    this.uploader.init(http, this.config);
  }
  
  upload(event) {
    let file = event.srcElement.files[0];

    this.uploader.upload(file).then((x) => {
      this.imagePath = x;
    });
  }
}

export class S3Config {
  bucket: string;
  accessKey: string;
  secretAccessKey: string;
  region: string;
  folder: string;
}

export class S3Uploader {
  private config: S3Config;
  private http: Http;

  init(http: Http, config: S3Config) {
    this.http = http;
    this.config = config;
  }

  upload(file: any): Promise<any> {
    let date = this.generateTimestamp();
    let datetime = date + 'T000000Z';

    let credential = `${this.config.accessKey}/${date}/${this.config.region}/s3/aws4_request`;

    let policy = JSON.stringify({
      "expiration": (new Date(Date.now() + 100000)).toISOString(),
      "conditions": [
        {"bucket": this.config.bucket},
        ["starts-with", "$key", ""],
        {"acl": "public-read"},
        ["starts-with", "$Content-Type", ""],
        {"x-amz-credential": credential},
        {"x-amz-algorithm": "AWS4-HMAC-SHA256"},
        {"x-amz-date": datetime}
      ]
    });

    let policyBase64 = window.btoa(policy);
    let signatureKey = this.generateSignatureKey(this.config.secretAccessKey, date, this.config.region, "s3");
    let signature = CryptoJS.HmacSHA256(policyBase64, signatureKey).toString(CryptoJS.enc.Hex);
    let formData = new FormData();

    formData.append('acl', "public-read");
    formData.append('Content-Type', file.type);
    formData.append('X-Amz-Date', datetime);
    formData.append('X-Amz-Algorithm', "AWS4-HMAC-SHA256");
    formData.append('X-Amz-Credential', credential);
    formData.append('X-Amz-Signature', signature);
    formData.append('Policy', policyBase64);
    formData.append('key', file.name);
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      this.http.post(`https://${this.config.bucket}.s3.amazonaws.com/`, formData).subscribe(x => {
        console.log(x);
        resolve(x.headers.get("Location"));
      }, x => {
        console.error(x);
        reject();
      });
    });
  }

  generateSignatureKey(key, dateStamp, regionName, serviceName) {
    let kDate = CryptoJS.HmacSHA256(dateStamp, "AWS4" + key);
    let kRegion = CryptoJS.HmacSHA256(regionName, kDate);
    let kService = CryptoJS.HmacSHA256(serviceName, kRegion);
    let kSigning = CryptoJS.HmacSHA256("aws4_request", kService);

    return kSigning;
  }

  generateTimestamp() {
    let date = new Date();
    let year = date.getFullYear();
    let month = ("0" + (date.getMonth() + 1)).slice(-2);
    let day = ("0" + date.getDate()).slice(-2);
    return year + month + day;
  }
}
# An example of uploading files to S3 by Angular2
See the [tutorial](http://swarm-discourse.cloudapp.net/t/an-example-of-uploading-files-to-s3-by-angular2/36)