Last update on Monday, May 23rd 2016

How to upload files to Amazon S3 with Angular 2 and Webpack

One recurrent question lately is: How the **** do I magically teleport files to AWS S3 using Angular 2?

Fear not! Here is the answer!

Installation

I’m using the stack from angular2-webpack-starter(How to install it Here) because it’s fast and preconfigured so adapt this tutorial to your case.

npm install aws-sdk

aws-sdk is not WebPack’s best friend so some work need to be done.

Thankfully, Andrew H Farger did the work for us here :D.

You will have a small warning saying that it’s precompiled. No big deal.

Now we are going to prevent errors from parsing and typings.

In Webpack dev conf add :

module: {

  noParse: [

   /aws-sdk/

  ]

}

In src/custom-typings.d.ts, add:

interface Window {
  AWS?: any;
}

Let's Code Now

You need to use the pre-compiled version of aws-sdk in dist otherwise you will have some errors.

In your component file, import aws-sdk:

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

require('aws-sdk/dist/aws-sdk');

In the template, just a file input, which on change will trigger fileEvent with the event:

<input type="file" (change)="fileEvent($event)" />

Get the AWSService from Window since AWS dist's puts it there and Voila! You have your AWS S3 ready to be loaded.

A very simple fileEvent method in the class.

Get the files -> select the first one -> configure AWS -> create a new S3 object and finally upload using this object and display the results.

export class ImportFilePage {
  constructor() {}

  fileEvent(fileInput: any) {
    var AWSService = window.AWS;

    var file = fileInput.target.files[0];

    AWSService.config.accessKeyId = "SpongeBob";

    AWSService.config.secretAccessKey = "Power";

    var bucket = new AWSService.S3({ params: { Bucket: "Ice" } });

    var params = { Key: file.name, Body: file };

    bucket.upload(params, function(err, data) {
      console.log(err, data);
    });
  }
}

It's as simple as this.

You might be interested in this analyze of the full-stack project created by the Ionic and AWS teams, many services from the new AWS Mobile Hub are detailed: AWS S3, Cognito, DynamoDB.

PS: I wrote this article with a focus on using AWS with Angular 2 and Webpack. In the comments you'll see how to make it secure by signing your credentials server-side with a Base64 policy.

How to upload files to Amazon S3 with Angular 2 and Webpack

How To Handle Typings Using Webpack ft Lodash

How Parcel simplifies modern JavaScript projects

Stay up to date


Join over 4000 other developers who already receive my tutorials and their source code out of the oven + other free stuff!