|
| 1 | +import { Component, OnInit } from '@angular/core'; |
| 2 | +import { UploadFileService } from 'src/app/services/upload-files.service'; |
| 3 | +import { HttpEventType, HttpResponse } from '@angular/common/http'; |
| 4 | +import { Observable } from 'rxjs'; |
| 5 | + |
| 6 | +@Component({ |
| 7 | + selector: 'app-upload-files', |
| 8 | + templateUrl: './upload-files.component.html', |
| 9 | + styleUrls: ['./upload-files.component.css'] |
| 10 | +}) |
| 11 | +export class UploadFilesComponent implements OnInit { |
| 12 | + |
| 13 | + selectedFiles: FileList; |
| 14 | + progressInfos = []; |
| 15 | + message = ''; |
| 16 | + |
| 17 | + fileInfos: Observable<any>; |
| 18 | + |
| 19 | + constructor(private uploadService: UploadFileService) { } |
| 20 | + |
| 21 | + ngOnInit() { |
| 22 | + this.fileInfos = this.uploadService.getFiles(); |
| 23 | + } |
| 24 | + |
| 25 | + selectFiles(event) { |
| 26 | + this.progressInfos = []; |
| 27 | + this.selectedFiles = event.target.files; |
| 28 | + } |
| 29 | + |
| 30 | + upload(idx, file) { |
| 31 | + this.progressInfos[idx] = { value: 0, fileName: file.name }; |
| 32 | + |
| 33 | + this.uploadService.upload(file).subscribe( |
| 34 | + event => { |
| 35 | + if (event.type === HttpEventType.UploadProgress) { |
| 36 | + this.progressInfos[idx].value = Math.round(100 * event.loaded / event.total); |
| 37 | + } else if (event instanceof HttpResponse) { |
| 38 | + this.fileInfos = this.uploadService.getFiles(); |
| 39 | + } |
| 40 | + }, |
| 41 | + err => { |
| 42 | + this.progressInfos[idx].value = 0; |
| 43 | + this.message = 'Could not upload the file:' + file.name; |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + uploadFiles() { |
| 48 | + this.message = ''; |
| 49 | + |
| 50 | + for (let i = 0; i < this.selectedFiles.length; i++) { |
| 51 | + this.upload(i, this.selectedFiles[i]); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments