Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { ChangeDetectorRef, Component, Input, NgZone, OnInit } from '@angular/core';
- import { ToastrService } from 'ngx-toastr';
- import { Observable } from 'rxjs';
- import { UploadFileService } from '../../../core/services/upload-service.service';
- @Component({
- selector: 'kt-upload-file',
- templateUrl: './upload-file.component.html',
- styleUrls: ['./upload-file.component.scss']
- })
- export class UploadFilesComponent implements OnInit {
- selectedFiles: FileList;
- progressInfos: any[] = [];
- message: string = '';
- fileCaricati: number = 0;
- @Input()
- carica: boolean = true;
- fileInfos: Observable<any>;
- constructor(private uploadService: UploadFileService,
- private zone: NgZone,
- private cdr: ChangeDetectorRef,
- private toastService: ToastrService) { }
- ngOnInit(): void {
- this.fileInfos = this.uploadService.getFiles();
- }
- selectFiles(event): void {
- this.progressInfos = [];
- this.selectedFiles = event;
- this.carica = true;
- this.uploadFiles();
- }
- uploadFiles(): void {
- if (this.selectedFiles) {
- for (let i = 0; i < this.selectedFiles.length; i++) {
- this.upload(i, this.selectedFiles[i]);
- }
- }
- }
- upload(idx: number, file: File): void {
- this.progressInfos[idx] = { value: 0, fileName: file.name };
- if (file) {
- if(file.size > 26214400) {
- this.message = 'File troppo grande, la dimensione massima consentita è di 25MB';
- this.progressInfos[idx].value = 0;
- this.toastService.warning(this.message);
- }
- else {
- this.isThisAFile(file).then(_ => {
- this.uploadService.upload(file).subscribe(
- _ => {
- this.zone.run(() => {
- this.cdr.detectChanges();
- this.progressInfos[idx].value = this.uploadService.progress;
- });
- },
- _ => {
- this.message = 'Errore nel caricamento del file ' + file.name;
- this.progressInfos[idx].value = 0;
- this.toastService.warning(this.message);
- }, () => {
- this.toastService.success("File " + file.name + " caricato con successo!");
- });
- }).catch(_ => {
- this.message = 'File non valido (non è possibile caricare cartelle)';
- this.progressInfos[idx].value = 0;
- this.toastService.warning(this.message);
- });
- }
- }
- }
- // https://stackoverflow.com/questions/52667995/how-to-check-if-selected-file-is-a-directory-or-regular-file
- isThisAFile(file) {
- return new Promise(function (resolve, reject) {
- if (file.type !== '') {
- return resolve(file)
- }
- const reader = new FileReader()
- reader.onloadend = () => {
- if (reader.error && reader.error.name === 'NotFoundError') {
- return reject(reader.error.name)
- }
- resolve(file)
- }
- reader.readAsBinaryString(file)
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement