Search code examples
angularamazon-s3angular2-components

Angular4 image upload to s3 bucket and storing the response.Location into a global variable which can be get access to other method/function


Hi am trying to upload image to amazon s3 server using angular 4 and now i want to fetch the response.Location which returns from the s3 as a url to a global variable which i can access that variable with the current response.Location url and i am unable to do so .....here is the code
HTML

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

ts

        import {ImageService} from './image.service';
        import {Image} from './image';

        export class UploadComponent {
           imagefile:any;
           file:any;
           url:any;

        constructor(private serviceSaveimageurl : ImageService) {}

      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, s3data) {
           console.log(err, s3data);
           this.url = s3data.Location  // here i want the url to be in this 
                                                                   variable
          });
       }


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

      module = new Image()
       saveImage(){
              console.log(this.url) // here i am getting it as undefine 
                                       after i get the s3data.Location need 
                                       help here 
             this.module.imageurl = this.url;
             this.serviceSaveimageurl.addImage(image)
               }

      }

Solution

  •   var objx = bucket.upload(params, function (err, s3data) {
          this.url = s3data;
        });
        this.gobj = objx;
    }
    
    fileEvent(fileInput: any){
        var files = fileInput.target.files;
        var file = files[0];
        this.file = file;
    }
    ImageModel = new CustomizerImages();
    saveImage(){
    
      console.log(this.gobj.url.Location)
    }