Загрузка файлов
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>
Свойства
Name | Type | Default | Description |
---|---|---|---|
name | string | null | Name of the request parameter to identify the files at backend. |
url | string | null | Remote url to upload the files. |
method | string | post | HTTP method to send the files to the url such as "post" and "put". |
multiple | boolean | false | Used to select multiple files at once from file dialog. |
accept | string | false | Pattern to restrict the allowed file types such as "image/*". |
disabled | boolean | false | Disables the upload functionality. |
auto | boolean | false | When enabled, upload begins automatically after selection is completed. |
maxFileSize | number | null | Maximum file size allowed in bytes. |
fileLimit | number | null | Maximum number of files that can be uploaded. |
invalidFileSizeMessageSummary | string | "0: Invalid file size, " | Summary message of the invalid file size. |
invalidFileSizeMessageDetail | string | "maximum upload size is 0." | Detail message of the invalid file size. |
invalidFileTypeMessageSummary | string | "0: Invalid file type, " | Summary message of the invalid file type. |
invalidFileLimitMessageDetail | string | "limit is 0 at most." | Detail message of the invalid file type. |
invalidFileLimitMessageSummary | string | "Maximum number of files exceeded, " | Summary message of the invalid file type. |
invalidFileTypeMessageDetail | string | "allowed file types: 0." | Detail message of the invalid file type. |
style | string | null | Inline style of the component. |
styleClass | string | null | Style class of the component. |
previewWidth | number | 50 | Width of the image thumbnail in pixels. |
chooseLabel | string | null | Label of the choose button. Defaults to global value in i18n translation configuration. |
uploadLabel | string | null | Label of the upload button. Defaults to global value in i18n translation configuration. |
cancelLabel | string | null | Label of the cancel button. Defaults to global value in i18n translation configuration. |
chooseIcon | string | pi pi-plus | Icon of the choose button. |
uploadIcon | string | pi pi-upload | Icon of the upload button. |
cancelIcon | string | pi pi-times | Icon of the cancel button. |
withCredentials | boolean | false | Cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. |
mode | string | advanced | Defines the UI of the component, possible values are "advanced" and "basic". |
customUpload | boolean | false | Whether to use the default upload or a manual implementation defined in uploadHandler callback. |
showUploadButton | boolean | true | Defines the visibility of upload button for Client-side FileUpload. |
showCancelButton | boolean | true | Defines the visibility of cancel button for Client-side FileUpload. |
files | array | null | List of files to be provide to the FileUpload externally. |
headers | HttpHeaders | null | HttpHeaders class represents the header configuration options for an HTTP request. |
События
Name | Parameters | Description |
---|---|---|
onBeforeUpload | event.formData: FormData object. | Callback to invoke before file upload is initialized. |
onSend | event.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. |
onUpload | event.originalEvent: Http Event<br>event.files: Uploaded files. | Callback to invoke when file upload is complete. |
onError | event.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. |
onRemove | event.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. |
onSelect | event.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. |
onProgress | event.originalEvent: Original browser event.<br>event.progress: Calculated progress value. | Callback to invoke when files are being uploaded. |
uploadHandler | event.files: List of selected files. | Callback to invoke in custom upload mode to upload the files manually. |
Методы
Name | Parameters | Description |
---|---|---|
upload | - | Uploads the selected files. |
clear | - | Clears the files list. |
Шаблоны
Name | Parameters |
---|---|
file | - |
content | $implicit: files |
toolbar | - |
Стилизация
Name | Element |
---|---|
p-fileupload | Container element |
p-fileupload-buttonbar | Header containing the buttons |
p-fileupload-content | Content section |