File

projects/angular-material-fileupload/src/lib/mat-file-upload/mat-file-upload.component.ts

Implements

OnInit OnDestroy

Metadata

changeDetection ChangeDetectionStrategy.OnPush
selector mat-file-upload
styleUrls ./mat-file-upload.component.scss
templateUrl ./mat-file-upload.component.html

Index

Properties
Methods
Inputs
Outputs
Accessors

Constructor

constructor(HttpClient: HttpClient, matFileUploadQueueService: MatFileUploadQueueService)
Parameters :
Name Type Optional
HttpClient HttpClient No
matFileUploadQueueService MatFileUploadQueueService No

Inputs

cancelAriaLabel
Default value : "Cancel File Upload"
file
Type : any
fileAlias
Type : string
fileUploadAriaLabel
Default value : "File Upload"
httpRequestHeaders
Type : HttpHeaders | literal type
httpRequestParams
Type : HttpParams | literal type
httpUrl
Type : string
id
Type : number

Outputs

onUpload
Type : EventEmitter
removeEvent
Type : EventEmitter

Output

Methods

ngOnDestroy
ngOnDestroy()
Returns : void
ngOnInit
ngOnInit()
Returns : void
Public remove
remove()
Returns : void
Public upload
upload()
Returns : void

Properties

Private _file
Type : any
Private _id
Type : number
Private fileUploadSubscription
Type : any
Public subs
Default value : new Subscription()
uploadInProgress$
Default value : this.uploadInProgressSubject.asObservable()
Private uploadInProgressSubject
Default value : new BehaviorSubject<boolean>(false)
uploadProgress$
Default value : this.uploadProgressSubject.asObservable()
Private uploadProgressSubject
Default value : new ReplaySubject<IUploadProgress>()

Accessors

file
setfile(file: any)
Parameters :
Name Type Optional
file any No
Returns : void
id
getid()
setid(id: number)
Parameters :
Name Type Optional
id number No
Returns : void
import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  OnDestroy,
  Input,
  Output,
  EventEmitter,
} from "@angular/core";
import { ReplaySubject, BehaviorSubject, Subscription } from "rxjs";
import {
  HttpHeaders,
  HttpParams,
  HttpClient,
  HttpEventType,
} from "@angular/common/http";
import { MatFileUploadQueueService } from "../mat-file-upload-queue/mat-file-upload-queue.service";
import { IUploadProgress } from "../mat-file-upload.type";

@Component({
  selector: "mat-file-upload",
  templateUrl: "./mat-file-upload.component.html",
  styleUrls: ["./mat-file-upload.component.scss"],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatFileUploadComponent implements OnInit, OnDestroy {
  private uploadProgressSubject = new ReplaySubject<IUploadProgress>();
  uploadProgress$ = this.uploadProgressSubject.asObservable();

  private uploadInProgressSubject = new BehaviorSubject<boolean>(false);
  uploadInProgress$ = this.uploadInProgressSubject.asObservable();

  public subs = new Subscription();

  /* Http request input bindings */
  @Input()
  httpUrl: string;

  @Input()
  httpRequestHeaders:
    | HttpHeaders
    | {
        [header: string]: string | string[];
      };

  @Input()
  httpRequestParams:
    | HttpParams
    | {
        [param: string]: string | string[];
      };

  @Input()
  fileAlias: string;

  private _file: any;
  private _id: number;

  @Input()
  get file(): any {
    return this._file;
  }
  set file(file: any) {
    this._file = file;
  }

  @Input()
  set id(id: number) {
    this._id = id;
  }
  get id(): number {
    return this._id;
  }

  @Input()
  fileUploadAriaLabel = "File Upload";

  @Input()
  cancelAriaLabel = "Cancel File Upload";

  /** Output  */
  @Output() removeEvent = new EventEmitter<MatFileUploadComponent>();
  @Output() onUpload = new EventEmitter();

  private fileUploadSubscription: any;

  constructor(
    private HttpClient: HttpClient,
    private matFileUploadQueueService: MatFileUploadQueueService
  ) {
    const queueInput = this.matFileUploadQueueService.getInputValue();
    if (queueInput) {
      this.httpUrl = this.httpUrl || queueInput.httpUrl;
      this.httpRequestHeaders =
        this.httpRequestHeaders || queueInput.httpRequestHeaders;
      this.httpRequestParams =
        this.httpRequestParams || queueInput.httpRequestParams;
      this.fileAlias = this.fileAlias || queueInput.fileAlias;
    }
  }

  ngOnInit() {
    this.uploadProgressSubject.next({
      progressPercentage: 0,
      loaded: 0,
      total: this._file.size,
    });
  }

  public upload(): void {
    this.uploadInProgressSubject.next(true);
    // How to set the alias?
    let formData = new FormData();
    formData.set(this.fileAlias, this._file, this._file.name);
    this.subs.add(
      this.HttpClient.post(this.httpUrl, formData, {
        headers: this.httpRequestHeaders,
        observe: "events",
        params: this.httpRequestParams,
        reportProgress: true,
        responseType: "json",
      }).subscribe(
        (event: any) => {
          if (event.type === HttpEventType.UploadProgress) {
            this.uploadProgressSubject.next({
              progressPercentage: Math.floor(
                (event.loaded * 100) / event.total
              ),
              loaded: event.loaded,
              total: event.total,
            });
          }
          this.onUpload.emit({ file: this._file, event: event });
        },
        (error: any) => {
          if (this.fileUploadSubscription) {
            this.fileUploadSubscription.unsubscribe();
          }
          this.uploadInProgressSubject.next(false);
          this.onUpload.emit({ file: this._file, event: event });
        },
        () => this.uploadInProgressSubject.next(false)
      )
    );
  }

  public remove(): void {
    this.subs.unsubscribe();
    this.removeEvent.emit(this);
  }

  ngOnDestroy() {
    this.subs.unsubscribe();
  }
}
<ng-container *ngIf="uploadProgress$ | async as uploadProgress">
  <mat-card>
    <span class="file-summary">{{ file.name }}({{ file.size | bytes }})</span>
    <div class="upload-progress">
      <mat-progress-bar
        [value]="uploadProgress.progressPercentage"
      ></mat-progress-bar>

      <button
        mat-icon-button
        [attr.aria-label]="fileUploadAriaLabel"
        (click)="upload()"
        [disabled]="uploadInProgress$ | async"
      >
        <mat-icon>file_upload</mat-icon>
      </button>

      <button
        mat-icon-button
        [attr.aria-label]="cancelAriaLabel"
        (click)="remove()"
      >
        <mat-icon>cancel</mat-icon>
      </button>
    </div>
    <span class="file-summary">{{ uploadProgress.progressPercentage }}%</span>
    <span>
      {{ uploadProgress.loaded | bytes }} of
      {{ uploadProgress.total | bytes }}</span
    >
  </mat-card>
</ng-container>

./mat-file-upload.component.scss

.file-summary {
  font-size: 0.85rem;
}

.upload-progress {
  display: flex;
  align-content: center;
  align-items: center;
  height: 10px;

  ::ng-deep .mat-progress-bar .mat-progress-bar-element {
    transition: none;
  }
}
Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""