# React Native File Upload (Pro)

> React Native file upload for iOS, Android and the web: a drag-and-drop Dropzone with paste and type, size and count checks, an upload list with thumbnails, progress, speed, time left, pause, resume, retry and cancel, a useUpload queue with your own adapter (S3, Uploadcare, Cloudinary, your API) and a concurrency limit, an avatar uploader with a circle crop, and a photo gallery uploader you reorder by dragging. Part of Patine Pro, no native modules.

# 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](#ios-and-android)).

```tsx
import { Dropzone, FileUploadList, useUpload, AvatarUploader, ImageGalleryUploader } from '@patine-ui/pro';
```

```tsx live
import { VStack } from 'patine-ui';
import { Dropzone, FileUploadList, mockUpload, useUpload } from '@patine-ui/pro';

export default function Example() {
  const queue = useUpload({
    // Your adapter goes here: see "Send files to your storage" below.
    upload: mockUpload({ speed: 900_000, fail: (name) => name.endsWith('.zip') }),
    accept: 'image/*,.pdf,.zip,.csv',
    maxSize: 25 * 1024 * 1024,
    maxFiles: 8,
  });
  return (
    <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.

```tsx live
import { useState } from 'react';
import { Box, Button, Text, TextArea, TextField } from 'patine-ui';
import { Dropzone, FileUploadList, mockUpload, useUpload } from '@patine-ui/pro';

export default function Example() {
  const queue = useUpload({
    upload: mockUpload({ speed: 400_000 }),
    accept: 'image/*,.pdf,.log,.txt',
    maxSize: 10 * 1024 * 1024,
    maxFiles: 5,
  });
  const [subject, setSubject] = useState('Export to CSV stops at 10,000 rows');
  const [sent, setSent] = useState(false);
  if (sent) return <Text>Request sent with {queue.files.length} attachments. We reply within a day.</Text>;
  return (
    <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.

```tsx live
import { useEffect } from 'react';
import { FileUploadList, mockUpload, useUpload } from '@patine-ui/pro';

const FILES = [
  { name: 'kitchen-wide.jpg', size: 3_400_000, type: 'image/jpeg', uri: 'https://images.unsplash.com/photo-1556911220-bff31c812dba?w=200&q=60' },
  { name: 'lease-agreement-signed-final-v3.pdf', size: 1_900_000, type: 'application/pdf' },
  { name: 'floor-plans.zip', size: 48_000_000, type: 'application/zip' },
  { name: 'Q4 budget.xlsx', size: 240_000 },
  { name: 'walkthrough.mp4', size: 92_000_000, type: 'video/mp4' },
];

export default function Example() {
  const queue = useUpload({
    upload: mockUpload({ speed: 700_000, fail: (name) => name.startsWith('lease') }),
    concurrency: 2,
  });
  useEffect(() => {
    queue.add(FILES);
  }, []);
  return <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.

```tsx live
import { useState } from 'react';
import { Text, VStack } from 'patine-ui';
import { Dropzone } from '@patine-ui/pro';

export default function Example() {
  const [files, setFiles] = useState([]);
  return (
    <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.

```tsx live
import { useState } from 'react';
import { VStack } from 'patine-ui';
import { AvatarUploader, mockUpload } from '@patine-ui/pro';

export default function Example() {
  const [photo, setPhoto] = useState(null);
  return (
    <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>
  );
}
```

## Photo gallery

`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`.

```tsx live
import { useEffect } from 'react';
import { ImageGalleryUploader, mockUpload, useUpload } from '@patine-ui/pro';

const photo = (id) => `https://images.unsplash.com/photo-${id}?w=500&q=70`;

export default function Example() {
  const gallery = useUpload({
    upload: mockUpload({ speed: 400_000 }),
    accept: 'image/*',
    maxFiles: 10,
    initialFiles: [
      { id: 'a', name: 'front.jpg', size: 2_100_000, type: 'image/jpeg', uri: photo('1600585154340-be6161a56a0c') },
      { id: 'b', name: 'living.jpg', size: 1_800_000, type: 'image/jpeg', uri: photo('1600607687939-ce8a6c25118c') },
      { id: 'c', name: 'garden.jpg', size: 2_600_000, type: 'image/jpeg', uri: photo('1600566753190-17f0baa2a6c3') },
    ],
  });
  useEffect(() => {
    gallery.add([{ name: 'kitchen.jpg', size: 2_900_000, type: 'image/jpeg', uri: photo('1600210492486-724fe5c67fb0') }]);
  }, []);
  return <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.

```tsx
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:

```tsx
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).

```tsx
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 };
};
```

```tsx
<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

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `upload` | `(file, { onProgress, signal }) => Promise<{ url?, response? }>` | — | Sends one file. Without it, files are only collected and checked. |
| `accept` | `string \| string[]` | — | MIME types and extensions: `'image/*,.pdf'`. |
| `maxSize`, `minSize` | `number` | — | Bytes. |
| `maxFiles` | `number` | — | How many the list may hold. |
| `concurrency` | `number` | `3` | Files uploading at once. |
| `autoUpload` | `boolean` | `true` | Start as files are added; otherwise call `start()`. |
| `initialFiles` | `PickedFile[]` | — | Files already uploaded, such as a saved gallery. |
| `onReject`, `onComplete`, `onSettled`, `onChange` | callbacks | — | Rejections; one file done; the queue done; any change. |
| `labels` | `Partial<UploadLabels>` | English | Messages 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

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `controller` | `UploadController` | — | Accepted files go into this queue, and its rules apply. |
| `onFiles` | `(accepted, rejected) => void` | — | Without a controller, the files picked. |
| `accept`, `maxSize`, `minSize`, `maxFiles` | | the controller's | Rules for this zone. |
| `multiple` | `boolean` | `true` unless `maxFiles` is 1 | Pick many. |
| `paste` | `boolean` | `false` | Take files pasted anywhere on the page (web). |
| `pickFiles` | `PickFiles` | the browser's on the web | Opens the picker on iOS and Android. |
| `size` | `'default' \| 'compact'` | `'default'` | A tall area or one row. |
| `title`, `description`, `icon` | `ReactNode` | | Replace the text and the cloud. |
| `showErrors` | `boolean` | `true` | List rejected files inside. |
| `children` | `ReactNode \| ({ dragging, open }) => ReactNode` | — | Your own content. |
| `disabled`, `accessibilityLabel`, `style`, `theme`, `design` | | | |

### FileUploadList

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `controller` | `UploadController` | **required** | From `useUpload`. |
| `density` | `'default' \| 'compact'` | `'default'` | Rows with thumbnails and speed, or one line each. |
| `showSummary` | `boolean` | with 2+ files | Count, total size and overall progress above. |
| `onPressFile` | `(file) => void` | — | Press a row, such as to preview it. |
| `labels`, `style`, `theme`, `design` | | | |

### AvatarUploader

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value`, `defaultValue` | `string \| null` | — | The photo's URI, controlled or not. |
| `onChange` | `(uri, file?) => void` | — | The new photo once cropped and uploaded (`null` when removed). |
| `upload` | `UploadAdapter` | — | Sends the cropped photo; without it the cropped URI is the value. |
| `pickFiles` | `PickFiles` | the browser's on the web | The photo picker on iOS and Android. |
| `cropFile` | `(file, crop) => Promise<PickedFile>` | — | Cuts the crop on iOS and Android (expo-image-manipulator). |
| `name` | `string` | — | For the initials and the label. |
| `size` | `number` | `96` | Points. |
| `maxSize` | `number` | 5 MB | Largest photo accepted. |
| `removable` | `boolean` | `true` | A Remove button. |
| `labels`, `disabled`, `style`, `theme`, `design` | | | |

### ImageGalleryUploader

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `controller` | `UploadController` | **required** | From `useUpload`, with `accept: 'image/*'` and usually `maxFiles`. |
| `columns` | `number` | fits the width (3 on a phone) | Columns. |
| `pickFiles` | `PickFiles` | the browser's on the web | The photo picker on iOS and Android. |
| `showCover` | `boolean` | `true` | Mark the first photo. |
| `sortable` | `boolean` | `true` | Drag and keys reorder. |
| `onPressItem` | `(file, index) => void` | — | Press a photo, such as to open it in an [ImageViewer](./image-viewer). |
| `labels`, `style`, `theme`, `design` | | | |

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

## Related

- [Image cropper](./image-cropper): the cropper inside `AvatarUploader`, on its own.
- [Image viewer](./image-viewer): open an uploaded photo full screen.
- [Progress](./progress): a bar or spinner by itself.
