File upload in Angular

Let us discuss how to do file upload in Angular.js in this session.

Create an HTML template with input tag of input type as file. Create a function to event for handling choosing files.

<div class="form-group">

    <label for="file">Choose File</label>

    <input type="file"

           id="file"

           (change)="handleFileInput($event.target.files)">

</div>

Now set a default variable for selected file.

fileToUpload: File = null;

Create  a function to use in event of your file input tag.

handleFileInput(files: FileList) {

    this.fileToUpload = files.item(0);

}

If you want to use multiple file selection then repeat through files array. The file upload function ie. file -upload-service:

postFile(fileToUpload: File): Observable<boolean> {

    const endpoint = 'your-destination-url';

    const formData: FormData = new FormData();

    formData.append('fileKey', fileToUpload, fileToUpload.name);

    return this.httpClient

      .post(endpoint, formData, { headers: yourHeadersConfig })

      .map(() => { return true; })

      .catch((e) => this.handleError(e));

}

Calling  file upload service:

uploadFileToActivity() {

    this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {

      // do something, if upload success

      }, error => {

        console.log(error);

      });

  }