'Upload images directly from an Angular application to AWS S3

I am currently following this tutorial to upload an image directly from my angular application onto an AWS S3 bucket. I made some minor changes to sort out the few errors that came up during my execution, however when I run my code I find that the function I use to select the image ("selectFile()") is not being executed when I click the button.

The code in my appcomponent.ts file is as follows:

export class AppComponent {
  selectedFiles: any = '';  //In the tutorial it was selectedFiles: FileList; But it kept throwing errors.
  imageSrc: string = '';

  constructor(private uploadService: UploadService) { }
  
  ngOnInit() {
  }
  
  upload() {
    const file = this.selectedFiles.item(0);
    this.uploadService.uploadFile(file);
  }
  
  selectFile(event: any) {
    const reader = new FileReader();
    if(event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      console.log(file.name);
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.imageSrc = reader.result as string;
      }
      this.selectedFiles = file;
    }
  }
}

UploadService:

import { Injectable } from '@angular/core';
import * as AWS from 'aws-sdk/global';
import * as S3 from 'aws-sdk/clients/s3';

@Injectable({
  providedIn: 'root'
})
export class UploadService {

  constructor() { }

  uploadFile(file: any) {
    const contentType = file.type;
    const bucket = new S3({
      accessKeyId: '...',
      secretAccessKey: '...',
      region: '...'
    });
    const params = {
      Bucket: '...',
      Key: file.name,
      Body: file,
      ACL: 'public-read',
      ContentType: contentType
    };
    bucket.upload(params, function(err: any, data: any){
      if (err) {
        console.log('There was an error uploading your file: ', err);
        return false;
      }
      console.log('Successfully uploaded file.', data);
      return true;
    });
    //for upload progress   
    /*bucket.upload(params).on('httpUploadProgress', function (evt) {
        console.log(evt.loaded + ' of ' + evt.total + ' Bytes');
      }).send(function (err, data) {
      if (err) {
        console.log('There was an error uploading your file: ', err);
        return false;
      }
      console.log('Successfully uploaded file.', data);
      return true;
    });*/
  }
}

And AppComponent.html is below:

<label class="btn btn-default">
  <img [src]="imageSrc" *ngIf="imageSrc" style="width:100%">
  <input type="file" (change)="selectFile($event)">
</label>

<button class="btn btn-success" [disabled]="!selectedFiles" (click)="upload()">Upload</button>

Where am I going wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source