primeng
Version:
[](https://opensource.org/licenses/MIT) [](https://badge.fury.io/js/primeng) [ • 24.6 kB
JavaScript
import { EventEmitter, ElementRef, NgZone, Input, Output, ContentChildren, ViewChild, Component, ChangeDetectionStrategy, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DomSanitizer } from '@angular/platform-browser';
import { ButtonModule } from 'primeng/button';
import { MessagesModule } from 'primeng/messages';
import { ProgressBarModule } from 'primeng/progressbar';
import { DomHandler } from 'primeng/dom';
import { PrimeTemplate, SharedModule } from 'primeng/api';
import { HttpEventType, HttpClient } from '@angular/common/http';
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var FileUpload = /** @class */ (function () {
function FileUpload(el, sanitizer, zone, http) {
this.el = el;
this.sanitizer = sanitizer;
this.zone = zone;
this.http = http;
this.method = 'POST';
this.invalidFileSizeMessageSummary = '{0}: Invalid file size, ';
this.invalidFileSizeMessageDetail = 'maximum upload size is {0}.';
this.invalidFileTypeMessageSummary = '{0}: Invalid file type, ';
this.invalidFileTypeMessageDetail = 'allowed file types: {0}.';
this.invalidFileLimitMessageDetail = 'limit is {0} at most.';
this.invalidFileLimitMessageSummary = 'Maximum number of files exceeded, ';
this.previewWidth = 50;
this.chooseLabel = 'Choose';
this.uploadLabel = 'Upload';
this.cancelLabel = 'Cancel';
this.chooseIcon = 'pi pi-plus';
this.uploadIcon = 'pi pi-upload';
this.cancelIcon = 'pi pi-times';
this.showUploadButton = true;
this.showCancelButton = true;
this.mode = 'advanced';
this.onBeforeUpload = new EventEmitter();
this.onSend = new EventEmitter();
this.onUpload = new EventEmitter();
this.onError = new EventEmitter();
this.onClear = new EventEmitter();
this.onRemove = new EventEmitter();
this.onSelect = new EventEmitter();
this.onProgress = new EventEmitter();
this.uploadHandler = new EventEmitter();
this._files = [];
this.progress = 0;
this.uploadedFileCount = 0;
}
Object.defineProperty(FileUpload.prototype, "files", {
get: function () {
return this._files;
},
set: function (files) {
this._files = [];
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (this.validate(file)) {
if (this.isImage(file)) {
file.objectURL = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(files[i])));
}
this._files.push(files[i]);
}
}
},
enumerable: true,
configurable: true
});
FileUpload.prototype.ngAfterContentInit = function () {
var _this = this;
this.templates.forEach(function (item) {
switch (item.getType()) {
case 'file':
_this.fileTemplate = item.template;
break;
case 'content':
_this.contentTemplate = item.template;
break;
case 'toolbar':
_this.toolbarTemplate = item.template;
break;
default:
_this.fileTemplate = item.template;
break;
}
});
};
FileUpload.prototype.ngAfterViewInit = function () {
var _this = this;
if (this.mode === 'advanced') {
this.zone.runOutsideAngular(function () {
if (_this.content)
_this.content.nativeElement.addEventListener('dragover', _this.onDragOver.bind(_this));
});
}
};
FileUpload.prototype.onFileSelect = function (event) {
if (event.type !== 'drop' && this.isIE11() && this.duplicateIEEvent) {
this.duplicateIEEvent = false;
return;
}
this.msgs = [];
if (!this.multiple) {
this.files = [];
}
var files = event.dataTransfer ? event.dataTransfer.files : event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!this.isFileSelected(file)) {
if (this.validate(file)) {
if (this.isImage(file)) {
file.objectURL = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(files[i])));
}
this.files.push(files[i]);
}
}
}
this.onSelect.emit({ originalEvent: event, files: files, currentFiles: this.files });
if (this.fileLimit && this.mode == "advanced") {
this.checkFileLimit();
}
if (this.hasFiles() && this.auto && (!(this.mode === "advanced") || !this.isFileLimitExceeded())) {
this.upload();
}
if (event.type !== 'drop' && this.isIE11()) {
this.clearIEInput();
}
else {
this.clearInputElement();
}
};
FileUpload.prototype.isFileSelected = function (file) {
var e_1, _a;
try {
for (var _b = __values(this.files), _c = _b.next(); !_c.done; _c = _b.next()) {
var sFile = _c.value;
if ((sFile.name + sFile.type + sFile.size) === (file.name + file.type + file.size)) {
return true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return false;
};
FileUpload.prototype.isIE11 = function () {
return !!window['MSInputMethodContext'] && !!document['documentMode'];
};
FileUpload.prototype.validate = function (file) {
if (this.accept && !this.isFileTypeValid(file)) {
this.msgs.push({
severity: 'error',
summary: this.invalidFileTypeMessageSummary.replace('{0}', file.name),
detail: this.invalidFileTypeMessageDetail.replace('{0}', this.accept)
});
return false;
}
if (this.maxFileSize && file.size > this.maxFileSize) {
this.msgs.push({
severity: 'error',
summary: this.invalidFileSizeMessageSummary.replace('{0}', file.name),
detail: this.invalidFileSizeMessageDetail.replace('{0}', this.formatSize(this.maxFileSize))
});
return false;
}
return true;
};
FileUpload.prototype.isFileTypeValid = function (file) {
var e_2, _a;
var acceptableTypes = this.accept.split(',').map(function (type) { return type.trim(); });
try {
for (var acceptableTypes_1 = __values(acceptableTypes), acceptableTypes_1_1 = acceptableTypes_1.next(); !acceptableTypes_1_1.done; acceptableTypes_1_1 = acceptableTypes_1.next()) {
var type = acceptableTypes_1_1.value;
var acceptable = this.isWildcard(type) ? this.getTypeClass(file.type) === this.getTypeClass(type)
: file.type == type || this.getFileExtension(file).toLowerCase() === type.toLowerCase();
if (acceptable) {
return true;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (acceptableTypes_1_1 && !acceptableTypes_1_1.done && (_a = acceptableTypes_1.return)) _a.call(acceptableTypes_1);
}
finally { if (e_2) throw e_2.error; }
}
return false;
};
FileUpload.prototype.getTypeClass = function (fileType) {
return fileType.substring(0, fileType.indexOf('/'));
};
FileUpload.prototype.isWildcard = function (fileType) {
return fileType.indexOf('*') !== -1;
};
FileUpload.prototype.getFileExtension = function (file) {
return '.' + file.name.split('.').pop();
};
FileUpload.prototype.isImage = function (file) {
return /^image\//.test(file.type);
};
FileUpload.prototype.onImageLoad = function (img) {
window.URL.revokeObjectURL(img.src);
};
FileUpload.prototype.upload = function () {
var _this = this;
if (this.customUpload) {
if (this.fileLimit) {
this.uploadedFileCount += this.files.length;
}
this.uploadHandler.emit({
files: this.files
});
}
else {
this.uploading = true;
this.msgs = [];
var formData_1 = new FormData();
this.onBeforeUpload.emit({
'formData': formData_1
});
for (var i = 0; i < this.files.length; i++) {
formData_1.append(this.name, this.files[i], this.files[i].name);
}
this.http.post(this.url, formData_1, {
headers: this.headers, reportProgress: true, observe: 'events', withCredentials: this.withCredentials
}).subscribe(function (event) {
switch (event.type) {
case HttpEventType.Sent:
_this.onSend.emit({
originalEvent: event,
'formData': formData_1
});
break;
case HttpEventType.Response:
_this.uploading = false;
_this.progress = 0;
if (event['status'] >= 200 && event['status'] < 300) {
if (_this.fileLimit) {
_this.uploadedFileCount += _this.files.length;
}
_this.onUpload.emit({ originalEvent: event, files: _this.files });
}
else {
_this.onError.emit({ files: _this.files });
}
_this.clear();
break;
case HttpEventType.UploadProgress: {
if (event['loaded']) {
_this.progress = Math.round((event['loaded'] * 100) / event['total']);
}
_this.onProgress.emit({ originalEvent: event, progress: _this.progress });
break;
}
}
}, function (error) {
_this.uploading = false;
_this.onError.emit({ files: _this.files, error: error });
});
}
};
FileUpload.prototype.clear = function () {
this.files = [];
this.onClear.emit();
this.clearInputElement();
};
FileUpload.prototype.remove = function (event, index) {
this.clearInputElement();
this.onRemove.emit({ originalEvent: event, file: this.files[index] });
this.files.splice(index, 1);
};
FileUpload.prototype.isFileLimitExceeded = function () {
if (this.fileLimit && this.fileLimit <= this.files.length + this.uploadedFileCount && this.focus) {
this.focus = false;
}
return this.fileLimit && this.fileLimit < this.files.length + this.uploadedFileCount;
};
FileUpload.prototype.isChooseDisabled = function () {
return this.fileLimit && this.fileLimit <= this.files.length + this.uploadedFileCount;
};
FileUpload.prototype.checkFileLimit = function () {
if (this.isFileLimitExceeded()) {
this.msgs.push({
severity: 'error',
summary: this.invalidFileLimitMessageSummary.replace('{0}', this.fileLimit.toString()),
detail: this.invalidFileLimitMessageDetail.replace('{0}', this.fileLimit.toString())
});
}
};
FileUpload.prototype.clearInputElement = function () {
if (this.advancedFileInput && this.advancedFileInput.nativeElement) {
this.advancedFileInput.nativeElement.value = '';
}
if (this.basicFileInput && this.basicFileInput.nativeElement) {
this.basicFileInput.nativeElement.value = '';
}
};
FileUpload.prototype.clearIEInput = function () {
if (this.advancedFileInput && this.advancedFileInput.nativeElement) {
this.duplicateIEEvent = true; //IE11 fix to prevent onFileChange trigger again
this.advancedFileInput.nativeElement.value = '';
}
};
FileUpload.prototype.hasFiles = function () {
return this.files && this.files.length > 0;
};
FileUpload.prototype.onDragEnter = function (e) {
if (!this.disabled) {
e.stopPropagation();
e.preventDefault();
}
};
FileUpload.prototype.onDragOver = function (e) {
if (!this.disabled) {
DomHandler.addClass(this.content.nativeElement, 'ui-fileupload-highlight');
this.dragHighlight = true;
e.stopPropagation();
e.preventDefault();
}
};
FileUpload.prototype.onDragLeave = function (event) {
if (!this.disabled) {
DomHandler.removeClass(this.content.nativeElement, 'ui-fileupload-highlight');
}
};
FileUpload.prototype.onDrop = function (event) {
if (!this.disabled) {
DomHandler.removeClass(this.content.nativeElement, 'ui-fileupload-highlight');
event.stopPropagation();
event.preventDefault();
var files = event.dataTransfer ? event.dataTransfer.files : event.target.files;
var allowDrop = this.multiple || (files && files.length === 1);
if (allowDrop) {
this.onFileSelect(event);
}
}
};
FileUpload.prototype.onFocus = function () {
this.focus = true;
};
FileUpload.prototype.onBlur = function () {
this.focus = false;
};
FileUpload.prototype.formatSize = function (bytes) {
if (bytes == 0) {
return '0 B';
}
var k = 1024, dm = 3, sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
FileUpload.prototype.onSimpleUploaderClick = function (event) {
if (this.hasFiles()) {
this.upload();
}
};
FileUpload.prototype.getBlockableElement = function () {
return this.el.nativeElement.children[0];
};
FileUpload.prototype.ngOnDestroy = function () {
if (this.content && this.content.nativeElement) {
this.content.nativeElement.removeEventListener('dragover', this.onDragOver);
}
};
FileUpload.ctorParameters = function () { return [
{ type: ElementRef },
{ type: DomSanitizer },
{ type: NgZone },
{ type: HttpClient }
]; };
__decorate([
Input()
], FileUpload.prototype, "name", void 0);
__decorate([
Input()
], FileUpload.prototype, "url", void 0);
__decorate([
Input()
], FileUpload.prototype, "method", void 0);
__decorate([
Input()
], FileUpload.prototype, "multiple", void 0);
__decorate([
Input()
], FileUpload.prototype, "accept", void 0);
__decorate([
Input()
], FileUpload.prototype, "disabled", void 0);
__decorate([
Input()
], FileUpload.prototype, "auto", void 0);
__decorate([
Input()
], FileUpload.prototype, "withCredentials", void 0);
__decorate([
Input()
], FileUpload.prototype, "maxFileSize", void 0);
__decorate([
Input()
], FileUpload.prototype, "invalidFileSizeMessageSummary", void 0);
__decorate([
Input()
], FileUpload.prototype, "invalidFileSizeMessageDetail", void 0);
__decorate([
Input()
], FileUpload.prototype, "invalidFileTypeMessageSummary", void 0);
__decorate([
Input()
], FileUpload.prototype, "invalidFileTypeMessageDetail", void 0);
__decorate([
Input()
], FileUpload.prototype, "invalidFileLimitMessageDetail", void 0);
__decorate([
Input()
], FileUpload.prototype, "invalidFileLimitMessageSummary", void 0);
__decorate([
Input()
], FileUpload.prototype, "style", void 0);
__decorate([
Input()
], FileUpload.prototype, "styleClass", void 0);
__decorate([
Input()
], FileUpload.prototype, "previewWidth", void 0);
__decorate([
Input()
], FileUpload.prototype, "chooseLabel", void 0);
__decorate([
Input()
], FileUpload.prototype, "uploadLabel", void 0);
__decorate([
Input()
], FileUpload.prototype, "cancelLabel", void 0);
__decorate([
Input()
], FileUpload.prototype, "chooseIcon", void 0);
__decorate([
Input()
], FileUpload.prototype, "uploadIcon", void 0);
__decorate([
Input()
], FileUpload.prototype, "cancelIcon", void 0);
__decorate([
Input()
], FileUpload.prototype, "showUploadButton", void 0);
__decorate([
Input()
], FileUpload.prototype, "showCancelButton", void 0);
__decorate([
Input()
], FileUpload.prototype, "mode", void 0);
__decorate([
Input()
], FileUpload.prototype, "headers", void 0);
__decorate([
Input()
], FileUpload.prototype, "customUpload", void 0);
__decorate([
Input()
], FileUpload.prototype, "fileLimit", void 0);
__decorate([
Output()
], FileUpload.prototype, "onBeforeUpload", void 0);
__decorate([
Output()
], FileUpload.prototype, "onSend", void 0);
__decorate([
Output()
], FileUpload.prototype, "onUpload", void 0);
__decorate([
Output()
], FileUpload.prototype, "onError", void 0);
__decorate([
Output()
], FileUpload.prototype, "onClear", void 0);
__decorate([
Output()
], FileUpload.prototype, "onRemove", void 0);
__decorate([
Output()
], FileUpload.prototype, "onSelect", void 0);
__decorate([
Output()
], FileUpload.prototype, "onProgress", void 0);
__decorate([
Output()
], FileUpload.prototype, "uploadHandler", void 0);
__decorate([
ContentChildren(PrimeTemplate)
], FileUpload.prototype, "templates", void 0);
__decorate([
ViewChild('advancedfileinput')
], FileUpload.prototype, "advancedFileInput", void 0);
__decorate([
ViewChild('basicfileinput')
], FileUpload.prototype, "basicFileInput", void 0);
__decorate([
ViewChild('content')
], FileUpload.prototype, "content", void 0);
__decorate([
Input()
], FileUpload.prototype, "files", null);
FileUpload = __decorate([
Component({
selector: 'p-fileUpload',
template: "\n <div [ngClass]=\"'ui-fileupload ui-widget'\" [ngStyle]=\"style\" [class]=\"styleClass\" *ngIf=\"mode === 'advanced'\">\n <div class=\"ui-fileupload-buttonbar ui-widget-header ui-corner-top\">\n <span class=\"ui-fileupload-choose\" [label]=\"chooseLabel\" [icon]=\"chooseIcon\" pButton [ngClass]=\"{'ui-state-focus': focus, 'ui-state-disabled':disabled || isChooseDisabled()}\"> \n <input #advancedfileinput type=\"file\" (change)=\"onFileSelect($event)\" [multiple]=\"multiple\" [accept]=\"accept\" [disabled]=\"disabled || isChooseDisabled()\" (focus)=\"onFocus()\" (blur)=\"onBlur()\">\n </span>\n\n <p-button *ngIf=\"!auto&&showUploadButton\" type=\"button\" [label]=\"uploadLabel\" [icon]=\"uploadIcon\" (onClick)=\"upload()\" [disabled]=\"!hasFiles() || isFileLimitExceeded()\"></p-button>\n <p-button *ngIf=\"!auto&&showCancelButton\" type=\"button\" [label]=\"cancelLabel\" [icon]=\"cancelIcon\" (onClick)=\"clear()\" [disabled]=\"!hasFiles() ||\u00A0uploading\"></p-button>\n\n <ng-container *ngTemplateOutlet=\"toolbarTemplate\"></ng-container>\n </div>\n <div #content [ngClass]=\"{'ui-fileupload-content ui-widget-content ui-corner-bottom':true}\"\n (dragenter)=\"onDragEnter($event)\" (dragleave)=\"onDragLeave($event)\" (drop)=\"onDrop($event)\">\n <p-progressBar [value]=\"progress\" [showValue]=\"false\" *ngIf=\"hasFiles()\"></p-progressBar>\n\n <p-messages [value]=\"msgs\" [enableService]=\"false\"></p-messages>\n\n <div class=\"ui-fileupload-files\" *ngIf=\"hasFiles()\">\n <div *ngIf=\"!fileTemplate\">\n <div class=\"ui-fileupload-row\" *ngFor=\"let file of files; let i = index;\">\n <div><img [src]=\"file.objectURL\" *ngIf=\"isImage(file)\" [width]=\"previewWidth\" /></div>\n <div>{{file.name}}</div>\n <div>{{formatSize(file.size)}}</div>\n <div>\n <button type=\"button\" icon=\"pi pi-times\" pButton (click)=\"remove($event,i)\" [disabled]=\"uploading\"></button>\n </div>\n </div>\n </div>\n <div *ngIf=\"fileTemplate\">\n <ng-template ngFor [ngForOf]=\"files\" [ngForTemplate]=\"fileTemplate\"></ng-template>\n </div>\n </div>\n <ng-container *ngTemplateOutlet=\"contentTemplate\"></ng-container>\n </div>\n </div>\n <span *ngIf=\"mode === 'basic'\" [ngClass]=\"{'ui-button ui-fileupload-choose ui-widget ui-state-default ui-corner-all ui-button-text-icon-left': true, \n 'ui-fileupload-choose-selected': hasFiles(),'ui-state-focus': focus, 'ui-state-disabled':disabled}\"\n [ngStyle]=\"style\" [class]=\"styleClass\" (mouseup)=\"onSimpleUploaderClick($event)\">\n <span class=\"ui-button-icon-left pi\" [ngClass]=\"{'pi-plus': !hasFiles()||auto, 'pi-upload': hasFiles()&&!auto}\"></span>\n <span class=\"ui-button-text ui-clickable\">{{auto ? chooseLabel : hasFiles() ? files[0].name : chooseLabel}}</span>\n <input #basicfileinput type=\"file\" [accept]=\"accept\" [multiple]=\"multiple\" [disabled]=\"disabled\"\n (change)=\"onFileSelect($event)\" *ngIf=\"!hasFiles()\" (focus)=\"onFocus()\" (blur)=\"onBlur()\">\n </span>\n ",
changeDetection: ChangeDetectionStrategy.Default
})
], FileUpload);
return FileUpload;
}());
var FileUploadModule = /** @class */ (function () {
function FileUploadModule() {
}
FileUploadModule = __decorate([
NgModule({
imports: [CommonModule, SharedModule, ButtonModule, ProgressBarModule, MessagesModule],
exports: [FileUpload, SharedModule, ButtonModule, ProgressBarModule, MessagesModule],
declarations: [FileUpload]
})
], FileUploadModule);
return FileUploadModule;
}());
/**
* Generated bundle index. Do not edit.
*/
export { FileUpload, FileUploadModule };
//# sourceMappingURL=primeng-fileupload.js.map