ഉള്ളടക്കത്തിലേക്ക് പോകുക
ബീറ്റ · പരീക്ഷണാത്മകംReact 19പിയർ ഡിപൻഡൻസികളില്ല

File Uploader

Drop, browse or paste files, validate them, and upload in chunks that can pause, resume and retry.

ബീറ്റ കമ്പോണന്റുകൾ മാറാൻ സാധ്യതയുണ്ട്; അവ നിങ്ങളുടെ കോഡ് തകരാറിലാക്കിയേക്കാം. സ്വന്തം ഉത്തരവാദിത്തത്തിൽ ഉപയോഗിക്കുക, ബഗ് ട്രാക്കർ വഴി അഭിപ്രായം അറിയിക്കുക.

ഈ പേജ് ഇതുവരെ വിവർത്തനം ചെയ്തിട്ടില്ല, അതിനാൽ ഇംഗ്ലീഷ് പതിപ്പാണ് താഴെ കാണിക്കുന്നത്.
ഈ പേജിൽ

Installation

npx gbs-add-block@latest -a FileUploader -beta

The block copies the file-uploader folder into your project, along with the small shared folder that every component imports. You own the code and can change it freely. There are no peer dependencies other than React.

Requirements

  • React 19 and @types/react 19
  • TypeScript target ES2022 or newer, with "jsx": "react-jsx"
  • Browsers from 2024 or newer (the styles use light-dark(), :has() and :dir())

Import the stylesheet once, for example in your global CSS:

css
@import "../component-lib/gbs.css";

or in your root layout / entry file:

ts
import "@/component-lib/gbs.css";

The FileUploader lets people drop, browse or paste files, checks them against your rules, and uploads them to your server in chunks. Each file shows its own progress and can be paused, resumed, retried or canceled. Several files upload at once, and failed chunks are retried with backoff. Image previews can be turned on or off, and files already on the server can be listed with download links. Without an endpoint it works as a better <input type="file"> inside a normal form.

Set the --gbs-* variables on :root to theme every component at once, the grid included. Each component's own variables fall back to them, and then to the built-in palette, so components look identical out of the box.

Default

Live preview

Quick Start

tsx
"use client";
 
import { FileUploader } from "@/component-lib/file-uploader";
 
export default function Attachments() {
  return (
    <FileUploader
      label="Attachments"
      multiple
      accept=".pdf,image/*"
      maxSize={20 * 1024 * 1024}
      endpoint="/api/upload"
      onUploadComplete={(items) =>
        console.log(items.map((item) => item.response))
      }
    />
  );
}

Selected files wait for the Upload button. Start them yourself with ref.current.upload(), or right away with autoUpload.

Your server needs to accept the chunk requests described in Upload Protocol. Server Implementation below has reference code for Node.js, Go, Java and .NET, plus curl commands to check any server.

In this section

This page covers the component: installing it, its props, and everything that happens in the browser. The server side is long enough to live on its own page.

PageWhat is in it
Upload Protocol & ServerThe wire protocol, a reference server, chunked uploads, custom transports

Props Table

Selection

PropTypeDefaultDescription
multiplebooleanfalseAllow several files. When false, a new file replaces the current one.
acceptstring—Same syntax as <input accept>: .pdf, image/*, application/json. Checked on drop and paste too.
maxFilesnumber—Total files, counting ones already selected. Ignored when multiple is false.
maxSizenumber—Bytes per file.
minSizenumber—Bytes per file.
validate(file: File) => string | null | undefined—Return a message to reject a file.
allowDuplicatesbooleanfalseKeep a file matching one already selected (same name, size and modified date).

Uploading

PropTypeDefaultDescription
endpointstring | (request: ChunkRequest) => string—Where chunks are sent. Without endpoint or transport, files are only selected.
method"POST" | "PUT" | "PATCH""POST"HTTP method.
headersRecord<string, string> | (request) => Record | Promise<Record>—Request headers. A function runs before each chunk, so tokens can refresh.
withCredentialsbooleanfalseSend cookies on cross-origin requests.
paramsobject | (file: File) => object—Extra data, sent as JSON in additionalParams with every chunk.
fieldNamesPartial<ChunkFieldNames>Go chunk-uploader namesRename the form fields. See Upload Protocol.
parseResponse(body: string, xhr: XMLHttpRequest) => unknownJSON, else textTurns each response into item.response.
transport(request: ChunkRequest) => Promise<unknown>HTTPReplaces the built-in sender. See Custom Transport.
chunkSizenumber5242880 (5 MiB)Bytes per request.
concurrencynumber3Files uploading at the same time.
retriesnumber3Extra attempts per chunk after a retryable failure.
retryDelaynumber1000First retry delay in ms; doubles on each attempt.
autoUploadbooleanfalseUpload as soon as files are added.
getFileId(item: UploadItem) => string | undefinedfrom the responseThe value posted for an uploaded file. See Forms.

Display and Form

PropTypeDefaultDescription
previewbooleantrueThumbnails for image files.
existingFilesExistingFile[]—Files already on the server, listed above new ones.
onRemoveExisting(file: ExistingFile) => void—Shows a remove button on existing files. Remove the file from your state here.
removablebooleantrueShow remove buttons.
labelReactNode—Field label.
descriptionReactNode—Hint below the drop zone.
errorReactNode—Error message below the drop zone; also marks it invalid.
requiredbooleanfalseMarks the label.
disabledbooleanfalseBlocks adding, uploading and removing.
size"sm" | "md" | "lg""md"Drop zone padding, thumbnail and font size.
namestring—Form field. See Forms.
idstringgeneratedId of the drop zone button.
localestringruntime localeFor file sizes and percentages.
classNamestring—Class for the root element.
classNamesPartial<Record<UploaderSlot, string>>—Classes per slot: root, label, dropzone, rejections, list, item, thumb, progress, actions, footer.
styleCSSProperties—Inline style for the root (e.g. CSS variables).
localeTextPartial<UploaderLocaleText>EnglishOverrides UI text. See Locale Text.
refRef<FileUploaderHandle>—Imperative API. See Imperative API.

Events

PropTypeDescription
onChange(files: File[]) => voidSelected files changed: added, removed or cleared.
onRejected(rejections: FileRejection[]) => voidFiles that failed validation, each with a code.
onFileSuccess(item: UploadItem) => voidA file finished uploading. item.response holds the server's last answer.
onFileError(item: UploadItem, error: unknown) => voidA file failed after its retries.
onUploadComplete(items: UploadItem[]) => voidEvery file in one upload run has stopped: uploaded, failed, paused or canceled.

UploadItem

ts
interface UploadItem {
  id: string; // stable row key
  uploadId: string; // sent with every chunk; new after a cancel
  file: File;
  status:
    | "idle"
    | "queued"
    | "uploading"
    | "paused"
    | "success"
    | "error"
    | "canceled";
  uploadedBytes: number;
  progress: number; // 0 to 1
  chunkSize: number;
  chunksDone: number;
  totalChunks: number;
  error?: string;
  response?: unknown; // the server's answer to the latest chunk
}

Previews

With preview (the default), image files show a thumbnail. Set preview={false} to show type icons only, for example for sensitive documents or long lists.

  • Thumbnails use object URLs, not base64. The browser doesn't copy the file into memory, and each URL is released when its row disappears.
  • Formats the browser can't draw, such as HEIC in most browsers, fall back to the image icon.
  • Other files show an icon for their kind: image, video, audio, PDF, spreadsheet, document, archive or other.

Existing Files

Show files saved earlier, for example when editing a record. The component doesn't fetch them; load them your way and pass them in:

tsx
const [existing, setExisting] = useState<ExistingFile[]>(record.attachments);
 
<FileUploader
  multiple
  endpoint="/api/upload"
  existingFiles={existing}
  onRemoveExisting={(file) =>
    setExisting((files) => files.filter((f) => f.id !== file.id))
  }
/>;
ts
interface ExistingFile {
  id: string;
  name: string;
  size?: number;
  type?: string;
  url?: string; // download link, and the preview for images
}

Validation

Files are checked when they are dropped, picked or pasted. Rejected files are listed with a reason, and onRejected receives them:

codeWhen
file-typeDoesn't match accept.
file-too-large / file-too-smallOutside maxSize / minSize.
too-many-filesOver maxFiles, or more than one file when multiple is false.
duplicateSame name, size and modified date as a selected file.
customvalidate returned a message; it's in rejection.message.
tsx
<FileUploader
  accept="image/*"
  validate={(file) =>
    file.name.length > 100 ? "File names can be up to 100 characters" : null
  }
/>

Client checks are for the user's convenience only. Check type and size on the server as well.

Forms

With a name, the uploader takes part in a normal form. What it posts depends on whether it uploads:

SetupPosts under namePosts under name-existing
With endpoint or transportThe stored id of each uploaded file: getFileId(item), else id / fileId / documentId / metadata.storedName from the responseIds of existingFiles
WithoutThe selected File objectsIds of existingFiles

Without an endpoint, a Server Action receives the files directly:

tsx
async function save(formData: FormData) {
  "use server";
  const files = formData.getAll("attachments") as File[];
}
 
<form action={save}>
  <FileUploader name="attachments" multiple />
  <button type="submit">Save</button>
</form>;

For large files, prefer an endpoint: chunks can resume, and Server Actions usually cap the body at 1 MB by default.

Imperative API (ref)

tsx
const uploader = useRef<FileUploaderHandle>(null);
 
<FileUploader ref={uploader} endpoint="/api/upload" multiple />;
 
const items = await uploader.current?.upload();
MethodSignatureDescription
open() => voidOpen the system file picker.
addFiles(files) => { accepted, rejected }Add files from code, with the same validation.
upload() => Promise<UploadItem[]>Upload every file not uploaded yet; resolves when they have all stopped.
pause(id?: string) => voidPause one file, or all.
cancel(id?: string) => voidCancel one file, or all.
clear() => voidAbort and remove every file.
getFiles() => File[]The selected files.
getItems() => UploadItem[]Files with their upload state.

Keyboard

KeysAction
TabReach the drop zone, then each file's buttons.
Enter / SpaceOpen the file picker from the drop zone, or press a row button.
Ctrl + V / ⌘ + VPaste files (e.g. a screenshot) while focus is in the uploader.

Accessibility: the drop zone is a real button whose name combines the label and the call to action, and whose hint lists the accepted types and limits. Each file's progress is a role="progressbar", and every row button is labelled with the file name ("Pause report.pdf"). Rejections are announced as alerts, and finished or failed uploads through a status region.

Styling and Theming

Rules ship unlayered, so a framework reset cannot strip them and a utility class passed through className still overrides them. Import the generated gbs.css once — see Theming.

tsx
<FileUploader classNames={{ dropzone: "min-h-40", item: "shadow-sm" }} />

CSS variables

Override them on .fu-root, on :root, or through style. Each variable falls back to the shared --gbs-* of the same name, then to the DataGrid's --dg-* when that stylesheet is loaded, and finally to the built-in palette.

VariableUsed for
--fu-font-sizeBase font size.
--fu-dropzone-pyVertical padding of the drop zone (set by size).
--fu-thumb-sizeThumbnail size (set by size).
--fu-bg, --fu-fgBackground and text color.
--fu-mutedHints, meta text and icons.
--fu-borderBorders; the drop zone uses a darker mix.
--fu-hoverHover background and the empty progress track.
--fu-input-bgDrop zone background.
--fu-accent, --fu-accent-fgProgress, the browse link and the Upload button.
--fu-accent-softDrop zone while dragging.
--fu-success"Uploaded" text.
--fu-dangerErrors and rejections.
--fu-focusFocus ring.
--fu-radiusCorner radius.

Dark mode

Colors follow the page's color-scheme. To force a scheme, put class="dark" or data-theme="dark" (or "light") on an ancestor such as <html>.

Data attributes

ElementAttributes
Root (.fu-root)data-size, data-disabled, data-invalid
Drop zone (.fu-dropzone)data-dragging
Row (.fu-item)data-status (idle, queued, uploading, paused, success, error, canceled), data-existing
Thumbnail (.fu-thumb)data-kind (image, video, audio, pdf, spreadsheet, document, archive, other)

Locale Text

tsx
<FileUploader
  locale="de-DE"
  localeText={{
    dropzone: "Dateien hierher ziehen oder",
    browse: "durchsuchen",
    upload: (count) => `${count} hochladen`,
    rejectTooLarge: (name, max) => `${name} ist größer als ${max}`,
  }}
/>
KeyDefault
dropzone / browse"Drag files here or" / "browse"
dropHere"Drop to add files"
hintTypes(types) => types
hintMaxSize(size) => "Up to {size} each"
hintMaxFiles(count) => "{count} files max"
upload(count) => "Upload {count} files"
cancelAll / clear / dismiss"Cancel all" / "Clear" / "Dismiss"
remove / cancel / pause / resume / retry / download(name) => "Remove {name}", …
queued / paused / uploaded / canceled / failed"Waiting" / "Paused" / "Uploaded" / "Canceled" / "Failed"
progress(sent, total, percent) => "{sent} of {total} · {percent}"
rejectFileType(name) => "{name} isn't an allowed file type"
rejectTooLarge / rejectTooSmall(name, limit) => "{name} is larger than {limit}", …
rejectTooMany(max) => "You can add up to {max} files"
rejectDuplicate(name) => "{name} is already added"
announceDone / announceFailed(name) => "{name} uploaded" / "{name} failed to upload"

File sizes and percentages follow locale.

Core Exports

useFileUploader(config) returns { store, items, rejections } for building a different UI on the same engine:

tsx
const { store, items } = useFileUploader({
  multiple: true,
  transport: createHttpTransport({ endpoint: "/api/upload" }),
});
 
<input
  type="file"
  multiple
  onChange={(event) => store.addFiles(event.target.files ?? [])}
/>;
<button onClick={() => store.upload()}>Upload</button>;

The framework-free core is exported from @/component-lib/file-uploader/core:

ExportDescription
createUploaderStore(config)The queue: addFiles, upload, pause, cancel, remove, clear, subscribe, getSnapshot.
createHttpTransport(options)The default XMLHttpRequest transport, with upload progress.
buildChunkForm(request, options)The multipart body for one chunk.
partitionFiles(incoming, existing, rules)Splits a selection into accepted and rejected files.
matchesAccept(file, accept)accept matching as the browser's picker does it.
summarize(items)Total bytes, overall progress and counts per status.
formatBytes(bytes, locale?) / fileKind(file) / readFileId(response)Display helpers.
UploadHttpError / isRetryable(error)Error type and retry rules.

Next.js

The component is a client component, and "use client" is already at the top of the files that need it. Upload to a Route Handler (see Server Implementation) rather than a Server Action: Server Actions buffer the whole body and are limited to 1 MB by default, while chunks keep every request small and resumable.

Nothing runs on the server: the store is created on the client, and no browser APIs are touched while rendering.

Migrating from the Previous Uploader

PreviousNew
apiURLendpoint
chunk_size (default 1 MB)chunkSize (default 5 MiB)
startUpload={true} toggled by the parentref.current.upload(), the Upload button, or autoUpload
uploadedFileIdArray={(ids) => …}onUploadComplete={(items) => …}; ids come from item.response or readFileId(item.response)
showImagePreview (default false)preview (default true)
fileCountmaxFiles
inputFileSize (megabytes)maxSize (bytes): inputFileSize={5} becomes maxSize={5 * 1024 * 1024}
selectedFiles / fileDataref.current.addFiles(files)
documentId={ids} (the component fetched ?id= itself)existingFiles={[{ id, name, size, url }]}; load them your way
isRemovable / removedIds={(id) => …}removable / onRemoveExisting={(file) => …}
onChange(files)Same name; receives every selected file
multiple, accept, disabledSame names
Fields file, originalname, originalFileSize; no chunkIndex for small fileschunk, fileName, fileSize, always chunkIndex / totalChunks, plus uploadId; rename with fieldNames
One request at a time for all filesFiles in parallel (concurrency), with retries and backoff
Errors logged to the console and skippedPer-file error state, retry button and onFileError
One overall progress animationProgress per file plus an overall bar
Duplicates matched by name onlyMatched by name, size and modified date
Base64 previews read with FileReaderObject URLs, released with the row
Click-only drop zone <div>Keyboard-accessible button, plus paste
Tailwind classes and injected <style> tagsstyles.css with --fu-* variables, classNames slots and data-* attributes

Notes

  • Chunks of one file are sent in order. Parallelism is across files.
  • Pausing aborts the chunk in flight, which is sent again on resume.
  • Progress is kept in memory: a page reload starts files over, although the server may still hold earlier chunks under the old uploadId.
  • Dropping a folder doesn't add the files inside it.