You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mohemm_srca/Mohem/src/app/hmg-common/ui/file-uploader/file-uploader.component.ts

101 lines
2.8 KiB
TypeScript

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { AlertController } from '@ionic/angular';
export interface CustomWindow extends Window {
File: any;
FileReader: any;
}
declare let window: CustomWindow;
@Component({
selector: 'file-uploader',
templateUrl: './file-uploader.component.html',
styleUrls: ['./file-uploader.component.scss']
})
export class FileUploaderComponent implements OnInit {
@Input() multiupload = false;
@Input() attachmentname = 'attachment-loader';
public attachmentData: string;
@Input() maxFileSize = 10 * 1024 * 1024;
@Output() fileSelected = new EventEmitter();
public inputFiles: any = [];
public attachmentImg = 'assets/icon/attachment.png';
public deleteImg = 'assets/icon/delete.png';
constructor(
public cs: CommonService,
public ts: TranslatorService,
public alertController: AlertController
) {
}
ngOnInit() {
}
public loadAttachment(changeEvent) {
const fileInput = this.getFileElement();
if (this.isFileSupported()) {
if (fileInput.files != null && fileInput.files.length > 0) {
const file = fileInput.files[0];
const reader = new FileReader();
if (file.size <= this.maxFileSize) {
reader.onload = (data) => {
if (this.multiupload) {
this.inputFiles.push({name: file.name, data: data.target['result']});
} else {
this.inputFiles = [{name: file.name, data: data.target['result']}];
}
this.fileSelected.emit( {
name: file.name ,
data: data.target['result'],
inputFiles: this.inputFiles
});
};
reader.readAsDataURL(file);
} else {
this.attachmentData = null;
changeEvent.target.value = ''; // remove current selection
this.showFileExceededMaxSize();
}
} else {
this.attachmentData = null;
}
}
}
private isFileSupported() {
return (window.FileReader && window.File);
}
private showFileExceededMaxSize() {
this.cs.presentConfirmDialog(
this.ts.trPK('general', 'large-file'),
() => {
this.openFile();
},
() => {
}
);
}
private getFileElement(): HTMLInputElement {
return document.getElementById(this.attachmentname) as HTMLInputElement;
}
public openFile() {
const fileInput = this.getFileElement();
fileInput.click();
}
public deleteFiles(index: number) {
this.inputFiles.splice(index, 1);
this.fileSelected.emit( {
name: null,
data: '',
inputFiles: this.inputFiles
});
}
}