Компоненты PrimeNG
FileUpload

Загрузка файлов

PrimeNG/FileUpload (opens in a new tab)

FileUpload - это продвинутый загрузчик с поддержкой перетаскивания, загрузкой нескольких файлов, автоматической загрузкой, отслеживанием прогресса и проверками.

С чего начать

Подключите модуль

import { FileUploadModule } from 'primeng-lts/fileupload';
import { HttpClientModule } from '@angular/common/http';

В .ts файле

import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/api';
 
@Component({
  selector: 'app-prime-fileupload',
  templateUrl: './prime-fileupload.component.html',
  styleUrls: ['./prime-fileupload.component.scss'],
  providers: [MessageService],
})
export class PrimeFileuploadComponent implements OnInit {
  constructor(private messageService: MessageService) {}
 
  uploadedFiles: any[] = [];
 
  ngOnInit(): void {}
 
  onUpload(event) {
    for (let file of event.files) {
      this.uploadedFiles.push(file);
    }
 
    this.messageService.add({ severity: 'info', summary: 'File Uploaded', detail: '' });
  }
 
  onBasicUpload(event) {
    for (let file of event.files) {
      this.uploadedFiles.push(file);
    }
 
    this.messageService.add({ severity: 'info', summary: 'File Uploaded', detail: '' });
  }
 
  onBasicUploadAuto(event) {
    for (let file of event.files) {
      this.uploadedFiles.push(file);
    }
 
    this.messageService.add({ severity: 'info', summary: 'File Uploaded', detail: '' });
  }
 
  uploadHandlerCstm(event) {
    console.log('custom');
  }
}

Встройте компонент с помощью тэга p-fileUpload.

<p-fileUpload name="myfile[]" url="./upload.php"></p-fileUpload>

Basic

<p-fileUpload
mode="basic"
name="demo[]"
url="./upload.php"
accept="image/*"
maxFileSize="1000000"
(onUpload)="onBasicUpload($event)"
></p-fileUpload>

Basic with Auto

<p-fileUpload
#fubauto
mode="basic"
name="demo[]"
url="./upload.php"
accept="image/*"
maxFileSize="1000000"
(onUpload)="onBasicUploadAuto($event)"
[auto]="true"
chooseLabel="Browse"
></p-fileUpload>

Advanced

Drag you files here

  • file.name - file.size bytes
<p-fileUpload
name="demo[]"
url="./upload.php"
(onUpload)="onUpload($event)"
multiple="multiple"
accept="image/*"
maxFileSize="1000000"
>
<ng-template pTemplate="content">
  <span>Drag you files here</span>
  <ul *ngIf="uploadedFiles.length">
    <li *ngFor="let file of uploadedFiles">{ { file.name } } - { { file.size } } bytes</li>
  </ul>
</ng-template>
</p-fileUpload>

Qpalette File Uploader

Загрузить

Загружайте файлы с помощью кнопок ниже. Форматы: jpg, png, pdf, doc, docx. Максимум 1mb.

file.name

<p-fileUpload
name="demo[]"
customUpload="true"
(uploadHandler)="uploadHandlerCstm($event)"
multiple="multiple"
accept="image/*"
maxFileSize="1000000"
chooseIcon="pi pi-cloud-upload"
chooseLabel="Добавить файл"
uploadLabel="Загрузить"
cancelLabel="Отмена"
styleClass="qpalette-file-uploader"
>
<ng-template pTemplate="toolbar">
  <header class="fileupload-header">
    <p style="margin-top: 8px"><b>Загрузить</b></p>
    <p class="text-small text-color-label">
      Загружайте файлы с помощью кнопкок ниже. Форматы: jpg, png, pdf, doc, docx. Максимум 1mb.
    </p>
  </header>
</ng-template>
 
<ng-template let-file pTemplate="file">
  <div class="fileupload-item">
    <i class="pi pi-file fileupload-file-icon"></i>
    <span class="fileupload-item-filename">{ { file.name } }</span>
    <i class="pi pi-trash fileupload-thrash-icon"></i>
  </div>
</ng-template>
</p-fileUpload>

Image Uploader

<p-fileUpload
  name="image[]"
  (uploadHandler)="uploadHandlerCstm($event)"
  accept="image/*"
  maxFileSize="1000000"
  [chooseIcon]="'pi pi-camera'"
  [chooseLabel]="' '"
  [showUploadButton]="false"
  [showCancelButton]="false"
  styleClass="image-uploader"
>
  <ng-template let-file pTemplate="file">
    <img [src]="file.objectURL" />
  </ng-template>
</p-fileUpload>
 
<p-fileUpload
  name="image[]"
  (uploadHandler)="uploadHandlerCstm($event)"
  accept="image/*"
  maxFileSize="1000000"
  [chooseIcon]="'pi pi-camera'"
  [chooseLabel]="' '"
  [showUploadButton]="false"
  [showCancelButton]="false"
  styleClass="image-uploader image-uploader--bg"
>
  <ng-template let-file pTemplate="file">
    <img [src]="file.objectURL" />
  </ng-template>
</p-fileUpload>
 
<p-fileUpload
  name="image[]"
  (uploadHandler)="uploadHandlerCstm($event)"
  accept="image/*"
  maxFileSize="1000000"
  [chooseIcon]="'pi pi-camera'"
  [chooseLabel]="' '"
  [showUploadButton]="false"
  [showCancelButton]="false"
  styleClass="image-uploader image-uploader--lg"
>
  <ng-template let-file pTemplate="file">
    <img [src]="file.objectURL" />
  </ng-template>
</p-fileUpload>
 
<p-fileUpload
  name="image[]"
  (uploadHandler)="uploadHandlerCstm($event)"
  accept="image/*"
  maxFileSize="1000000"
  [chooseIcon]="'pi pi-camera'"
  [chooseLabel]="' '"
  [showUploadButton]="false"
  [showCancelButton]="false"
  styleClass="image-uploader image-uploader--lg image-uploader--bg"
>
  <ng-template let-file pTemplate="file">
    <img [src]="file.objectURL" />
  </ng-template>
</p-fileUpload>

Image Uploader Fluid

<p-fileUpload
name="image[]"
(uploadHandler)="uploadHandlerCstm($event)"
accept="image/*"
maxFileSize="1000000"
[chooseIcon]="'pi pi-camera'"
[chooseLabel]="' '"
[showUploadButton]="false"
[showCancelButton]="false"
styleClass="image-uploader image-uploader--lg image-uploader--bg"
>
<ng-template let-file pTemplate="file">
  <img [src]="file.objectURL" />
</ng-template>
</p-fileUpload>

Свойства

NameTypeDefaultDescription
namestringnullName of the request parameter to identify the files at backend.
urlstringnullRemote url to upload the files.
methodstringpostHTTP method to send the files to the url such as "post" and "put".
multiplebooleanfalseUsed to select multiple files at once from file dialog.
acceptstringfalsePattern to restrict the allowed file types such as "image/*".
disabledbooleanfalseDisables the upload functionality.
autobooleanfalseWhen enabled, upload begins automatically after selection is completed.
maxFileSizenumbernullMaximum file size allowed in bytes.
fileLimitnumbernullMaximum number of files that can be uploaded.
invalidFileSizeMessageSummarystring"0: Invalid file size, "Summary message of the invalid file size.
invalidFileSizeMessageDetailstring"maximum upload size is 0."Detail message of the invalid file size.
invalidFileTypeMessageSummarystring"0: Invalid file type, "Summary message of the invalid file type.
invalidFileLimitMessageDetailstring"limit is 0 at most."Detail message of the invalid file type.
invalidFileLimitMessageSummarystring"Maximum number of files exceeded, "Summary message of the invalid file type.
invalidFileTypeMessageDetailstring"allowed file types: 0."Detail message of the invalid file type.
stylestringnullInline style of the component.
styleClassstringnullStyle class of the component.
previewWidthnumber50Width of the image thumbnail in pixels.
chooseLabelstringnullLabel of the choose button. Defaults to global value in i18n translation configuration.
uploadLabelstringnullLabel of the upload button. Defaults to global value in i18n translation configuration.
cancelLabelstringnullLabel of the cancel button. Defaults to global value in i18n translation configuration.
chooseIconstringpi pi-plusIcon of the choose button.
uploadIconstringpi pi-uploadIcon of the upload button.
cancelIconstringpi pi-timesIcon of the cancel button.
withCredentialsbooleanfalseCross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates.
modestringadvancedDefines the UI of the component, possible values are "advanced" and "basic".
customUploadbooleanfalseWhether to use the default upload or a manual implementation defined in uploadHandler callback.
showUploadButtonbooleantrueDefines the visibility of upload button for Client-side FileUpload.
showCancelButtonbooleantrueDefines the visibility of cancel button for Client-side FileUpload.
filesarraynullList of files to be provide to the FileUpload externally.
headersHttpHeadersnullHttpHeaders class represents the header configuration options for an HTTP request.

События

NameParametersDescription
onBeforeUploadevent.formData: FormData object.Callback to invoke before file upload is initialized.
onSendevent.originalEvent: Http Event<br>event.formData: FormData object.An event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream.
onUploadevent.originalEvent: Http Event<br>event.files: Uploaded files.Callback to invoke when file upload is complete.
onErrorevent.files: Files that are not uploaded.<br>event.error: Request Error.Callback to invoke if file upload fails.
onClear-Callback to invoke when files in queue are removed without uploading using clear all button.
onRemoveevent.originalEvent: Original browser event.<br>event.file: Selected file.Callback to invoke when a file is removed without uploading using clear button of a file.
onSelectevent.originalEvent: Original browser event.<br>event.files: Selected files of the select event. event.currentFiles: All files to be uploaded.Callback to invoke when files are selected.
onProgressevent.originalEvent: Original browser event.<br>event.progress: Calculated progress value.Callback to invoke when files are being uploaded.
uploadHandlerevent.files: List of selected files.Callback to invoke in custom upload mode to upload the files manually.

Методы

NameParametersDescription
upload-Uploads the selected files.
clear-Clears the files list.

Шаблоны

NameParameters
file-
content$implicit: files
toolbar-

Стилизация

NameElement
p-fileuploadContainer element
p-fileupload-buttonbarHeader containing the buttons
p-fileupload-contentContent section