File

src/app/shared/components/file-upload/file-upload.component.ts

Implements

OnInit OnChanges OnDestroy

Metadata

selector crm-file-upload
styleUrls file-upload.component.scss
templateUrl ./file-upload.component.html

Index

Properties
Methods
Inputs
Outputs

Constructor

constructor(authService: AuthService, http: AuthHttp)
Parameters :
Name Type Optional Description
authService AuthService
http AuthHttp

Inputs

byOne

Type: boolean

Default value: false

id

Type: string

limit

Type: number

Default value: 20

maxFileSize

Type: number

Default value: 20000000

readonly

Type: boolean

Default value: false

tag

Type: string

uploadedFilesIds

Type: string[]

Default value: []

Outputs

removeFile $event type: EventEmitter
uploadResponse $event type: EventEmitter

Methods

fileOverBase
fileOverBase(e: )
Parameters :
Name Type Optional Description
e
Returns : void
Private getFileData
getFileData()
Returns : void
isMoreThenLimit
isMoreThenLimit()
Returns : boolean
ngOnChanges
ngOnChanges(changes: SimpleChanges)
Parameters :
Name Type Optional Description
changes SimpleChanges
Returns : void
ngOnDestroy
ngOnDestroy()
Returns : void
ngOnInit
ngOnInit()
Returns : void
onDownload
onDownload(fileData: FileData)
Parameters :
Name Type Optional Description
fileData FileData
Returns : void
onRemoveUploaded
onRemoveUploaded(fileData: FileData)
Parameters :
Name Type Optional Description
fileData FileData
Returns : void
progressValue
progressValue()
Returns : any
showUploadButton
showUploadButton()
Returns : boolean

Properties

componentId
componentId: string
Type : string
Private fileDataSubscription
fileDataSubscription: Subscription
Type : Subscription
fileUploader
fileUploader: FileUploader
Type : FileUploader
hasBaseDropZoneOver
hasBaseDropZoneOver: boolean
Type : boolean
Default value : false
uploadedFiles
uploadedFiles: FileData[]
Type : FileData[]
Default value : []
import {Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, OnDestroy} from "@angular/core";
import {FileUploader, ParsedResponseHeaders} from "ng2-file-upload";
import {FileData} from "./file-data";
import {AuthService} from "../../../core/auth/auth.service";
import {AuthHttp} from "../../../core/auth/auth-http.service";
import {Subscription} from "rxjs";
import * as FileSaver from "file-saver";

@Component({
  selector: 'crm-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent implements OnInit, OnChanges, OnDestroy {

  constructor(private authService: AuthService, private http: AuthHttp) {
  }

  @Input() tag: string;
  @Input() id: string;
  @Input() uploadedFilesIds: string[] = [];
  @Input() readonly: boolean = false;
  @Output() uploadResponse = new EventEmitter<string>();
  @Output() removeFile = new EventEmitter<string>();
  @Input() limit: number = 20;
  @Input() byOne: boolean = false;
  @Input() maxFileSize: number = 20000000; //in bytes

  uploadedFiles: FileData[] = [];

  componentId: string;
  fileUploader: FileUploader;
  hasBaseDropZoneOver: boolean = false;

  private fileDataSubscription: Subscription;

  fileOverBase(e) {
    this.hasBaseDropZoneOver = e;
  }

  progressValue() {
    if (!this.fileUploader.progress) {
      return 0;
    } else {
      return this.fileUploader.progress;
    }
  }

  onDownload(fileData: FileData) {
    this.http.download('/api/v1/files/' + fileData.uuid).subscribe(
      response => {
        let contentType: string = response.headers.get('content-type');
        let blob = new Blob([response.blob()], {type: contentType});
        FileSaver.saveAs(blob, fileData.name);
      },
      error => console.error("Can't load file", error)
    )
  }

  onRemoveUploaded(fileData: FileData) {
    this.uploadedFiles.splice(this.uploadedFiles.indexOf(fileData), 1);
    this.removeFile.emit(fileData.uuid);
  }

  isMoreThenLimit() {
    return this.limit && this.limit <= (this.uploadedFiles.length + this.fileUploader.queue.length)
  }

  private getFileData() {
    if (this.uploadedFilesIds && this.uploadedFilesIds.filter(Boolean).length > 0) {
      this.fileDataSubscription = this.http.post('/api/v1/files', JSON.stringify(this.uploadedFilesIds.filter(Boolean)))
        .map(res => res.json())
        .subscribe(
          filesData => this.uploadedFiles = filesData,
          error => console.log(error)
        )
    }
  }

  showUploadButton() {
    return this.fileUploader.queue.length > 0;
  }

  ngOnInit() {
    this.componentId = 'file-upload-' + this.id;
    const options = {
      url: '/api/v1/files/' + this.tag,
      maxFileSize: this.maxFileSize,
      queueLimit: this.limit,
      headers: [{name: this.authService.getHeaderName(), value: this.authService.getToken()}]
    };
    this.fileUploader = new FileUploader(options);
    this.fileUploader.onCompleteItem = (item: any, response: string, status: number, headers: ParsedResponseHeaders) => {
      const responseJson = JSON.parse(response);
      this.uploadedFiles.push(responseJson);
      item.remove();
      this.uploadResponse.emit(responseJson.uuid);
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['uploadedFilesIds']) {
      this.getFileData();
    }
  }

  ngOnDestroy() {
    if (this.fileDataSubscription) {
      this.fileDataSubscription.unsubscribe()
    }
  }
}
<div class="row" #row>
  <div class="col-md-1 col-sm-12" *ngIf="!readonly && !isMoreThenLimit()">

    <div ng2FileDrop
         [uploader]="fileUploader"
         (fileOver)="fileOverBase($event)"
         [ngClass]="{'btn-outline-primary': hasBaseDropZoneOver}"
         class="file-upload-container btn btn-secondary">

      <label [attr.for]="componentId" class="btn file-upload-label">
        <i class="icon-cloud-upload"></i><span> Choose file <br> or drag it here</span>
      </label>

      <input type="file" [attr.id]="componentId" ng2FileSelect [uploader]="fileUploader" [multiple]="!byOne">

    </div>
  </div>

  <div class="col-sm-12"
       [ngClass]="{'col-md-11': !readonly && !isMoreThenLimit() && row.offsetWidth > 400,
                   'col-md-12': readonly || isMoreThenLimit() || row.offsetWidth <= 400}">

    <table class="table table-custom">
      <thead>
      <tr>
        <th class="files-td">File name</th>
        <th class="files-td status" *ngIf="!readonly">Status</th>
        <th class="files-td" width="80"><!--Actions--></th>
      </tr>
      </thead>
      <tbody>

      <tr *ngFor="let item of uploadedFiles">
        <td class="files-td text-truncate file-name" title="{{item.name}}">
          {{item.name}}
        </td>
        <td class="files-td status" *ngIf="!readonly">
          <span class="is-uploaded">Uploaded</span>
        </td>
        <td class="files-td">
          <div class="pull-right">
            <button type="button" class="btn btn-link text-muted action-padding" title="Download file"
                    (click)="onDownload(item)">
              <span class="fa fa-download fa-lg"></span>
            </button>
            <button type="button" class="btn btn-link text-muted action-padding" title="Delete file"
                    (click)="onRemoveUploaded(item)" *ngIf="!readonly">
              <span class="fa fa-trash fa-lg"></span>
            </button>
          </div>
        </td>
      </tr>

      <tr *ngFor="let item of fileUploader.queue">
        <td class="files-td text-truncate file-name" title="{{item.file.name}}">
          {{item.file.name}}
        </td>
        <td class="files-td status" *ngIf="!readonly">
          <span *ngIf="item.isUploaded" class="is-uploaded">Uploaded</span>
          <span *ngIf="item.isUploading" class="uploading">Uploading</span>
          <span *ngIf="!item.isUploading && !item.isUploaded" class="not-uploaded">Not uploaded</span>
        </td>
        <td class="files-td">
          <div class="pull-right">
            <button type="button" class="btn btn-link text-muted action-padding" title="Delete file" (click)="item.remove()">
              <span class="fa fa-trash fa-lg"></span>
            </button>
          </div>
        </td>
      </tr>
      </tbody>
    </table>
    <!--<progress class="progress progress-xs progress-info progress-custom" max="100"-->
              <!--value="{{progressValue()}}"></progress>-->
    <button type="button" class="btn btn-primary btn-sm" (click)="fileUploader.uploadAll()" *ngIf="!readonly && showUploadButton()">Upload</button>
    <!--<button class="btn btn-danger btn-sm" (click)="fileUploader.clearQueue()">Remove all</button>-->
  </div>

</div>
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""