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 });
<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 and size validation, upload progress, and drag-and-drop state. See Primitive for a component-based API.
Features#
- Validation pipeline — enforces
acceptpatterns (including wildcards),maxFileSize, andfileLimitwith human-readable messages instate.messages - Upload transport — built-in XMLHttpRequest POST with FormData and progress reporting, or bring-your-own via
customUpload+uploadHandler - Drag-and-drop surface —
contentPropswires the drop zone events and exposesdata-highlightduring drag-over - File and upload state —
state.files,state.uploadedFiles,state.progress, andhasFiles/hasUploadedFilesbooleans for rendering - Imperative controls —
choose,upload,clear,remove(index), andremoveUploadedFile(index)for custom UI - File-level prop getters —
fileProps,fileThumbnailProps,fileInfoProps,fileNameProps,fileSizeProps, andfileRemovePropsfor each row formatSize(bytes)— utility for rendering human-readable file sizes
Working with callbacks#
Server upload with lifecycle hooks#
Set url and name for the built-in XHR transport and tap into the lifecycle to log, mutate headers, or surface errors.
const fileupload = useFileUpload({
url: '/api/upload',
name: 'files[]',
onBeforeSend: (e) => e.xhr.setRequestHeader('x-csrf', csrf),
onProgress: (e) => setProgress(e.progress),
onUpload: (e) => toast.success(`Uploaded ${e.files.length} files`),
onError: (e) => toast.error(`Failed: ${e.xhr.status}`)
});Auto upload after selection#
Set auto so files post immediately — useful for avatars or drag-drop drop zones without a separate submit step.
const fileupload = useFileUpload({
auto: true,
url: '/api/upload',
name: 'files'
});Custom client-side processing#
Set customUpload and provide uploadHandler when you need to resize images, strip EXIF, or hand files off to a signed-URL flow.
const fileupload = useFileUpload({
customUpload: true,
uploadHandler: async (e) => {
await uploadToS3(e.files);
e.options.clear();
}
});Rendering the file list#
Iterate state.files and spread the file-level getters for consistent data-scope / data-part attributes on each row.
<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>Surfacing validation messages#
Read state.messages to render toasts or inline errors when files fail accept, maxFileSize, or fileLimit checks.
{
fileupload.state.messages.map((msg, i) => (
<div key={i} role="alert">
{msg}
</div>
));
}Styling with data attributes#
The drop zone lights up via data-highlight="true" during drag-over; every prop object exposes a data-part for CSS targeting.
[data-scope='fileupload'][data-part='content'][data-highlight='true'] {
border-color: var(--primary);
background: var(--primary-bg);
}
[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#
Space or Enter opens the file picker, and dropped files trigger onSelect with standard drag events. See Primitive for full WAI-ARIA compliance details.