Skip to main content

File upload Pro

Everything between "choose a file" and "it's on your server", at the level of Uploadcare and Filestack but inside your app. Dropzone takes files dropped, browsed or pasted and checks them against accept, maxSize and maxFiles, saying why it turned any away. useUpload is the queue: it sends files through your own upload(file, { onProgress, signal }) a few at a time and tracks each one's bytes, speed, time left and errors. FileUploadList draws that queue with pause, resume, retry and cancel. AvatarUploader and ImageGalleryUploader are the two flows apps need most: a profile photo cropped in a circle, and a grid of listing photos you drag into order.

It uses React Native core only. The web has its own file picker and drag and drop; on iOS and Android pass pickFiles built on expo-document-picker or expo-image-picker (below).

import { Dropzone, FileUploadList, useUpload, AvatarUploader, ImageGalleryUploader } from '@patine-ui/pro';
Loading…
<VStack gap="md" style={{ width: '100%', maxWidth: 560 }}>
  <Dropzone controller={queue} paste />
  <FileUploadList controller={queue} />
</VStack>

Drop a few files on it, click it, or paste a screenshot. Files ending in .zip fail on purpose here, so you can try Retry.

Example: attachments on a support request​

A help-center form: screenshots and logs upload while the person writes, the files sit in a compact list under the message, and Send waits until every upload has finished.

Loading…
<Box border radius="lg" padding="lg" gap="md" style={{ width: '100%', maxWidth: 520 }}>
  <TextField label="Subject" value={subject} onChangeText={setSubject} />
  <TextArea label="What happened?" placeholder="Steps, what you expected, what you saw" />
  <Dropzone controller={queue} size="compact" title="Add screenshots or logs" />
  {queue.files.length ? <FileUploadList controller={queue} density="compact" /> : null}
  <Button disabled={queue.busy || !subject.trim()} onPress={() => setSent(true)}>
    {queue.busy ? 'Waiting for uploads…' : 'Send request'}
  </Button>
</Box>

A queue with work in progress​

What a real queue looks like mid-upload: a photo almost done, a PDF that lost its connection, an archive still going, a spreadsheet that landed. Each row shows bytes sent, speed and time left while it moves; pause, resume, retry and cancel act on that file only, and the summary above sums them all.

Loading…
<FileUploadList controller={queue} style={{ width: '100%', maxWidth: 560 }} />

density="compact" gives one dense line per file, for a sidebar or a form.

Check files before they upload​

The rules sit on useUpload (or on a Dropzone by itself): accept takes MIME types and extensions as <input accept> does, maxSize and minSize are bytes, maxFiles counts what's already in the list. The zone writes the rules under its title ("PDF · up to 10 MB") unless you give a description, and lists every file it turned away with the reason. onReject gets them too, with a code (file-invalid-type, file-too-large, file-too-small, too-many-files) to show your own message.

Loading…
<VStack gap="sm" style={{ width: '100%', maxWidth: 520 }}>
  <Dropzone
    size="compact"
    accept="application/pdf"
    maxSize={10 * 1024 * 1024}
    maxFiles={1}
    title="Attach your signed contract"
    onFiles={(accepted) => setFiles(accepted)}
  />
  <Text size="sm" color="textSecondary">
    {files.length ? `Ready: ${files[0].name}` : 'Try a PDF, then an image.'}
  </Text>
</VStack>

Profile photo​

AvatarUploader is the settings-page avatar: press it, pick a photo, crop it in a circle (drag, pinch or scroll to zoom, rotate), and the cropped photo shows at once with a ring of progress around it while it uploads. A failed upload keeps the photo and turns the camera badge into Retry. Initials stand in when there's no photo. The web crops with a canvas into a 512-pixel JPEG; on iOS and Android, cropFile hands you the crop to cut with expo-image-manipulator.

Loading…
<VStack gap="lg">
  <AvatarUploader name="Maya Lindqvist" value={photo} onChange={setPhoto} upload={mockUpload({ speed: 120_000 })} />
  <AvatarUploader name="Leo Brandt" defaultValue="https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=300&q=70" size={72} />
</VStack>

ImageGalleryUploader is the photo step of a listing, a post or a product: tiles in a grid that fits its width, each upload's progress over its thumbnail, Retry on a failed one, ✕ to remove, and the first marked Cover. Drag a tile to reorder: hold it on a touch screen, just drag with a mouse; Shift + arrow keys move the focused one. On the web, drop photos anywhere on the grid. The order is the controller's files.

Loading…
<ImageGalleryUploader controller={gallery} style={{ width: '100%', maxWidth: 560 }} />

Send files to your storage​

The adapter is one function: it gets the file (name, size, type, uri, and on the web the browser's file), reports bytes with onProgress, stops when signal aborts (pause, cancel, remove), and resolves with the file's url or throws to mark it failed. Its error message is shown on the row.

xhrUpload(url) is a ready one for your own endpoint: multipart form data through XMLHttpRequest, which (unlike fetch) reports upload progress on every platform.

import { useUpload, xhrUpload } from '@patine-ui/pro';

const queue = useUpload({ upload: xhrUpload('https://api.example.com/files', { headers: { Authorization: `Bearer ${token}` } }) });

For S3 or R2, ask your server for a presigned URL, then PUT the file to it:

const s3Upload = async (file, { onProgress, signal }) => {
const { uploadUrl, publicUrl } = await fetch('/api/presign', {
method: 'POST',
body: JSON.stringify({ name: file.name, type: file.type }),
signal,
}).then((r) => r.json());
// On the web it's the File; on iOS and Android, read the file at its URI.
const body = file.file ?? (await fetch(file.uri).then((r) => r.blob()));
await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('PUT', uploadUrl);
xhr.setRequestHeader('Content-Type', file.type);
xhr.upload.onprogress = (e) => onProgress(e.loaded, e.total);
xhr.onload = () => (xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`)));
xhr.onerror = () => reject(new Error('Network error'));
signal.addEventListener('abort', () => xhr.abort());
xhr.send(body);
});
return { url: publicUrl };
};

A resumable service (tus, Uploadcare's multipart) can start from file.loaded after a pause; a plain upload starts over, and the bar follows what onProgress reports. mockUpload({ speed, fail }) pretends, for demos and tests.

iOS and Android​

There's no file picker in React Native itself, so pass pickFiles to Dropzone, AvatarUploader or ImageGalleryUploader. It gets { accept, multiple } and resolves with the picked files (or [] when cancelled).

import * as DocumentPicker from 'expo-document-picker';
import * as ImagePicker from 'expo-image-picker';

export const pickDocuments = async ({ multiple }) => {
const result = await DocumentPicker.getDocumentAsync({ multiple, copyToCacheDirectory: true });
if (result.canceled) return [];
return result.assets.map((a) => ({ name: a.name, size: a.size ?? 0, type: a.mimeType, uri: a.uri }));
};

export const pickPhotos = async ({ multiple }) => {
const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], allowsMultipleSelection: multiple, quality: 0.9 });
if (result.canceled) return [];
return result.assets.map((a) => ({
name: a.fileName ?? `photo-${Date.now()}.jpg`,
size: a.fileSize ?? 0,
type: a.mimeType ?? 'image/jpeg',
uri: a.uri,
width: a.width,
height: a.height,
}));
};

// The avatar crops natively with expo-image-manipulator:
import { manipulateAsync, FlipType, SaveFormat } from 'expo-image-manipulator';

export const cropFile = async (file, crop) => {
const result = await manipulateAsync(
file.uri,
[
{ crop: { originX: crop.x, originY: crop.y, width: crop.width, height: crop.height } },
...(crop.flipX ? [{ flip: FlipType.Horizontal }] : []),
...(crop.rotation ? [{ rotate: crop.rotation }] : []),
{ resize: { width: 512 } },
],
{ compress: 0.9, format: SaveFormat.JPEG }
);
return { name: 'avatar.jpg', type: 'image/jpeg', uri: result.uri, size: 0, width: result.width, height: result.height };
};
<Dropzone controller={queue} pickFiles={pickDocuments} />
<AvatarUploader pickFiles={pickPhotos} cropFile={cropFile} upload={s3Upload} />
<ImageGalleryUploader controller={gallery} pickFiles={pickPhotos} />

Designs​

  • Brand and Material: a soft tile with a dashed edge and the icon on a raised disc; each file a card.
  • iOS: a quieter tile, and files as rows in one inset group with hairlines between them.
  • Web: the browser's familiar dashed box on the page background, with a stronger edge.

Accessibility​

  • The zone is a button named "Upload files", its rules read as the hint; Enter and Space open the picker. Rejected files are announced (role="alert") and each has a Dismiss button.
  • Each file's row reads its name and status ("2.4 MB of 8 MB · 1.2 MB/s · 5s left"); every action names its file ("Pause hero.jpg"). The summary is a polite live region.
  • Gallery tiles say their place ("Photo 2 of 5, Cover"), take the screen reader actions Move earlier, Move later and Remove, and on the web Shift + arrows move them and Delete removes them.
  • Every button is at least 44pt to touch; the ✕ and camera badges draw smaller with a wider touch area. Motion (the zone lighting up, checks popping in, tiles making way) follows reduce motion.

Props​

useUpload​

OptionTypeDefaultDescription
upload(file, { onProgress, signal }) => Promise<{ url?, response? }>—Sends one file. Without it, files are only collected and checked.
acceptstring | string[]—MIME types and extensions: 'image/*,.pdf'.
maxSize, minSizenumber—Bytes.
maxFilesnumber—How many the list may hold.
concurrencynumber3Files uploading at once.
autoUploadbooleantrueStart as files are added; otherwise call start().
initialFilesPickedFile[]—Files already uploaded, such as a saved gallery.
onReject, onComplete, onSettled, onChangecallbacks—Rejections; one file done; the queue done; any change.
labelsPartial<UploadLabels>EnglishMessages and action names, for translation.

It returns { files, add, start, pause, resume, retry, remove, clear, move, replace, progress, busy, rules }. Each file is { id, name, size, type, uri, status: 'queued' | 'uploading' | 'paused' | 'success' | 'error', loaded, speed, error?, url? }.

Dropzone​

PropTypeDefaultDescription
controllerUploadController—Accepted files go into this queue, and its rules apply.
onFiles(accepted, rejected) => void—Without a controller, the files picked.
accept, maxSize, minSize, maxFilesthe controller'sRules for this zone.
multiplebooleantrue unless maxFiles is 1Pick many.
pastebooleanfalseTake files pasted anywhere on the page (web).
pickFilesPickFilesthe browser's on the webOpens the picker on iOS and Android.
size'default' | 'compact''default'A tall area or one row.
title, description, iconReactNodeReplace the text and the cloud.
showErrorsbooleantrueList rejected files inside.
childrenReactNode | ({ dragging, open }) => ReactNode—Your own content.
disabled, accessibilityLabel, style, theme, design

FileUploadList​

PropTypeDefaultDescription
controllerUploadControllerrequiredFrom useUpload.
density'default' | 'compact''default'Rows with thumbnails and speed, or one line each.
showSummarybooleanwith 2+ filesCount, total size and overall progress above.
onPressFile(file) => void—Press a row, such as to preview it.
labels, style, theme, design

AvatarUploader​

PropTypeDefaultDescription
value, defaultValuestring | null—The photo's URI, controlled or not.
onChange(uri, file?) => void—The new photo once cropped and uploaded (null when removed).
uploadUploadAdapter—Sends the cropped photo; without it the cropped URI is the value.
pickFilesPickFilesthe browser's on the webThe photo picker on iOS and Android.
cropFile(file, crop) => Promise<PickedFile>—Cuts the crop on iOS and Android (expo-image-manipulator).
namestring—For the initials and the label.
sizenumber96Points.
maxSizenumber5 MBLargest photo accepted.
removablebooleantrueA Remove button.
labels, disabled, style, theme, design

ImageGalleryUploader​

PropTypeDefaultDescription
controllerUploadControllerrequiredFrom useUpload, with accept: 'image/*' and usually maxFiles.
columnsnumberfits the width (3 on a phone)Columns.
pickFilesPickFilesthe browser's on the webThe photo picker on iOS and Android.
showCoverbooleantrueMark the first photo.
sortablebooleantrueDrag and keys reorder.
onPressItem(file, index) => void—Press a photo, such as to open it in an ImageViewer.
labels, style, theme, design

Also exported: xhrUpload, mockUpload, browserPickFiles, validateFiles, describeRules, formatBytes, fileKind.