Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 File upload for Amazon s3 bucket

I know how to do amazon s3 file upload in angular 1. May i know how to upload file in angular 2. but i didn't find any solution for angular 2.

like image 738
Deepak Avatar asked Mar 15 '16 11:03

Deepak


2 Answers

It still needs better/some security.

html

<form  (ngSubmit)="onSubmit(f)" #f="ngForm" action="">
<input type="file" (change)="fileEvent($event)" />
</form>
<button (click)="uploadfile(f)">Upload file!</button>

ts

export class Page2 {
    myfile:any;
    file:any;

constructor() {
}


   uploadfile(event) {
        AWS.config.accessKeyId = 'YOUR-ACCESS-KEY';
        AWS.config.secretAccessKey = 'YOU-SECRET-ACCESS-KEY';
        var bucket = new AWS.S3({params: {Bucket: 'YOUR-BUCKET-NAME'}});
        var params = {Key: this.file.name, Body: this.file};
        bucket.upload(params, function (err, data) {
            console.log(err, data);
        });
    }


    fileEvent(fileInput: any){
        var files = event.target.files;
        var file = files[0];
        this.file = file;
    }

}
like image 186
CESCO Avatar answered Nov 18 '22 18:11

CESCO


If you are using a Rails backend (or even Node) the easiest solution is to create a presigned url (which must be a PUT) and then use an Angular service to call that PUT and attach the file in the body of the request.

You can read more about how I did that here.

like image 4
rmcsharry Avatar answered Nov 18 '22 17:11

rmcsharry