useFileUpload
Hook that manages file selection, validation, upload progress, and drag-and-drop state.
Usage#
import { useFileUpload } from '@primereact/headless/fileupload';
const fileupload = useFileUpload({ accept: 'image/*', multiple: true });
return (
<div {...fileupload.rootProps}>
<input {...fileupload.inputProps} />
<button {...fileupload.chooseProps}></button>
<button {...fileupload.uploadProps}></button>
<div {...fileupload.contentProps}>
<div {...fileupload.fileListProps}>
<div {...fileupload.fileProps}>
<img {...fileupload.fileThumbnailProps} />
<div {...fileupload.fileInfoProps}>
<div {...fileupload.fileNameProps}></div>
<div {...fileupload.fileSizeProps}></div>
</div>
<button {...fileupload.fileRemoveProps}></button>
</div>
</div>
</div>
</div>
);useFileUpload manages file selection, type/size validation, upload progress, and drag-and-drop — see Primitive for a component-based API.
Features#
- Returns spread-ready prop objects (
inputProps,contentProps,fileListProps,fileProps,fileThumbnailProps,fileInfoProps,fileNameProps,fileSizeProps,fileRemoveProps) with data attributes and event handlers - File type validation against
acceptpatterns including wildcards (image/*) - File size validation with configurable
maxFileSizelimit - File count restriction via
fileLimit - Upload progress tracking via XMLHttpRequest with
state.progress - Imperative methods:
choose(),upload(),clear(),remove(index),removeUploadedFile(index) - Exposes
state.files,state.uploadedFiles,state.messages,state.progress - Utility:
formatSize(bytes)for human-readable file sizes hasFilesandhasUploadedFilescomputed booleans
Behavior#
File Type Restriction#
Set accept to restrict file types using MIME types or extensions. Supports wildcard patterns like image/*.
const fileupload = useFileUpload({ accept: 'image/*' });Multiple Files#
Set multiple to allow selecting more than one file at a time.
const fileupload = useFileUpload({ multiple: true });Max File Size#
Set maxFileSize in bytes to validate file sizes. Invalid files produce messages in state.messages.
const fileupload = useFileUpload({ maxFileSize: 1000000 }); // 1MBFile Limit#
Set fileLimit to restrict the total number of files that can be uploaded.
const fileupload = useFileUpload({ fileLimit: 5 });Auto Upload#
Set auto to upload files immediately after selection without a manual upload step.
const fileupload = useFileUpload({ auto: true, url: '/api/upload', name: 'files' });Server Upload#
Set url and name to upload files via XMLHttpRequest POST. The hook handles FormData construction and progress tracking.
const fileupload = useFileUpload({
url: '/api/upload',
name: 'files[]',
onUpload: (e) => console.log('Uploaded', e.files),
onError: (e) => console.log('Error', e.xhr.status)
});Custom Upload#
Set customUpload and provide uploadHandler to override the default XMLHttpRequest upload with custom logic.
const fileupload = useFileUpload({
customUpload: true,
uploadHandler: (e) => {
// Process files client-side
e.options.clear();
}
});Upload Lifecycle Callbacks#
The hook provides callbacks for each stage of the upload lifecycle.
const fileupload = useFileUpload({
url: '/api/upload',
name: 'files',
onBeforeUpload: (e) => {
/* customize xhr before send */
},
onBeforeSend: (e) => {
/* modify formData or headers */
},
onProgress: (e) => console.log(e.progress + '%'),
onUpload: (e) => console.log('Success'),
onError: (e) => console.log('Failed')
});Removing Files#
Use remove(index) to remove a pending file and removeUploadedFile(index) to remove an uploaded file. Both trigger the onRemove callback.
fileupload.remove(0); // Remove first pending file
fileupload.removeUploadedFile(0); // Remove first uploaded fileDrag-and-Drop Feedback#
The contentProps object includes drag event handlers and a callback ref for the drop zone. The content element receives data-highlight="true" during drag-over.
[data-scope='fileupload'][data-part='content'][data-highlight='true'] {
border-color: var(--primary);
background: var(--primary-bg);
}File-Level Prop Getters#
The hook returns prop getter objects for each file-level element. Spread these on corresponding DOM elements to apply data-scope and data-part attributes.
<div {...fileupload.fileListProps}>
{fileupload.state.files.map((file, i) => (
<div key={file.name + file.size} {...fileupload.fileProps}>
<img {...fileupload.fileThumbnailProps} src={URL.createObjectURL(file)} />
<div {...fileupload.fileInfoProps}>
<div {...fileupload.fileNameProps}>{file.name}</div>
<div {...fileupload.fileSizeProps}>{fileupload.formatSize(file.size)}</div>
</div>
<button {...fileupload.fileRemoveProps} onClick={() => fileupload.remove(i)}>
Remove
</button>
</div>
))}
</div>Formatting File Sizes#
Use formatSize(bytes) to convert byte counts to human-readable strings.
fileupload.formatSize(1048576); // "1 MB"Custom Styling with Data Attributes#
[data-scope='fileupload'][data-part='content'] { ... }
[data-scope='fileupload'][data-part='file'] { ... }
[data-scope='fileupload'][data-part='fileThumbnail'] { ... }
[data-scope='fileupload'][data-part='fileInfo'] { ... }
[data-scope='fileupload'][data-part='fileName'] { ... }
[data-scope='fileupload'][data-part='fileSize'] { ... }
[data-scope='fileupload'][data-part='fileList'] { ... }
[data-scope='fileupload'][data-part='fileRemove'] { ... }API#
useFileUpload#
| Name | Type | Default |
|---|---|---|
name | string | — |
| Name of the request parameter to identify the files at backend. | ||
url | string | — |
| Remote url to upload the files. | ||
multiple | boolean | false |
| Used to select multiple files at once from file dialog. | ||
accept | string | — |
| Pattern to restrict the allowed file types such as "image/*". | ||
disabled | boolean | false |
| When present, it specifies that the element should be disabled. | ||
auto | boolean | false |
| When enabled, upload begins automatically after selection is completed. | ||
maxFileSize | number | — |
| Maximum file size allowed in bytes. | ||
fileLimit | number | — |
| Maximum number of files that can be uploaded. | ||
withCredentials | boolean | false |
| Cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. | ||
customUpload | boolean | false |
| Whether to use the default upload or a manual implementation defined in uploadHandler callback. | ||
invalidFileLimitMessage | string | 'Maximum number of files exceeded, limit is {0} at most.' |
| Message to display when number of files to be uploaded exceeds the limit. | ||
invalidFileSizeMessage | string | '{0}: Invalid file size, file size should be smaller than {1}.' |
| Message to display when file size exceeds the limit. | ||
invalidFileTypeMessage | string | '{0}: Invalid file type, allowed file types: {1}.' |
| Message to display when file type is not allowed. | ||
uploadHandler | (event: FileUploadHandlerEvent) => void | — |
| Callback to invoke to implement a custom upload. | ||
onSelect | (event: FileUploadSelectEvent) => void | — |
| Callback to invoke when files are selected. | ||
onBeforeUpload | (event: FileUploadBeforeUploadEvent) => void | — |
| Callback to invoke before file upload begins to customize the request such as post parameters before the files. | ||
onUpload | (event: FileUploadUploadEvent) => void | — |
| Callback to invoke when file upload is complete. | ||
onError | (event: FileUploadErrorEvent) => void | — |
| Callback to invoke if file upload fails. | ||
onProgress | (event: FileUploadProgressEvent) => void | — |
| Callback to invoke on upload progress. | ||
onBeforeSend | (event: FileUploadBeforeSendEvent) => void | — |
| Callback to invoke before send for customization such as adding headers. | ||
onClear | () => void | — |
| Callback to invoke when files in queue are removed without uploading. | ||
onRemove | (event: FileUploadRemoveEvent) => void | — |
| Callback to invoke when a file is removed. | ||
Accessibility#
See FileUpload Primitive for WAI-ARIA compliance details and keyboard support.