Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/expo-rn-formdata-uri.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@uploadthing/expo": patch
---

fix: give expo File uploads a filesystem uri
2 changes: 2 additions & 0 deletions packages/expo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"eslint": "9.25.1",
"expo-constants": "^16.0.0",
"expo-document-picker": "^12.0.1",
"expo-file-system": "^17.0.1",
"expo-image-picker": "^15.0.4",
"react": "19.2.2",
"react-native": "^0.74.1",
Expand All @@ -59,6 +60,7 @@
"peerDependencies": {
"expo-constants": "*",
"expo-document-picker": "*",
"expo-file-system": "*",
"expo-image-picker": "*",
"react": "^17.0.2 || ^18.0.0 || ^19.0.0",
"react-native": "*",
Expand Down
35 changes: 34 additions & 1 deletion packages/expo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { FileRouter } from "uploadthing/types";
import { peerDependencies } from "../package.json";
import { GENERATE_useDocumentUploader } from "./document-picker";
import { GENERATE_useImageUploader } from "./image-picker";
import { toRNFormDataFile } from "./rn-formdata";

export interface GenerateTypedHelpersOptions {
/**
Expand Down Expand Up @@ -81,5 +82,37 @@ export const generateReactNativeHelpers = <TRouter extends FileRouter>(
const useImageUploader = GENERATE_useImageUploader<TRouter>(opts);
const useDocumentUploader = GENERATE_useDocumentUploader<TRouter>(opts);

return { ...vanillaHelpers, useImageUploader, useDocumentUploader };
const useUploadThing: typeof vanillaHelpers.useUploadThing = (
endpoint,
hookOpts,
) => {
return vanillaHelpers.useUploadThing(endpoint, {
...hookOpts,
// `useUploadThing` applies `onBeforeUploadBegin` inside `startUpload`,
// so convert after the user callback can replace files.
onBeforeUploadBegin: async (files) => {
const maybeReplaced =
(await hookOpts?.onBeforeUploadBegin?.(files)) ?? files;
return Promise.all(maybeReplaced.map(toRNFormDataFile));
},
});
};

const uploadFiles: typeof vanillaHelpers.uploadFiles = async (
slug,
uploadOpts,
) => {
return vanillaHelpers.uploadFiles(slug, {
...uploadOpts,
files: await Promise.all(uploadOpts.files.map(toRNFormDataFile)),
});
};

return {
...vanillaHelpers,
useUploadThing,
uploadFiles,
useImageUploader,
useDocumentUploader,
};
};
77 changes: 77 additions & 0 deletions packages/expo/src/rn-formdata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import * as FileSystem from "expo-file-system";

const BASE64_ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/**
* Binary-safe base64 encoder. Reads the buffer as a Uint8Array in 3-byte
* groups (each byte masked to 0-255) so we never go through `btoa`/`Blob`
* APIs that are unreliable with binary data in React Native.
*/
const arrayBufferToBase64 = (buffer: ArrayBuffer): string => {
const bytes = new Uint8Array(buffer);
let result = "";

for (let i = 0; i < bytes.length; i += 3) {
const remaining = bytes.length - i;
const byte1 = (bytes[i] ?? 0) & 0xff;
const byte2 = remaining > 1 ? (bytes[i + 1] ?? 0) & 0xff : 0;
const byte3 = remaining > 2 ? (bytes[i + 2] ?? 0) & 0xff : 0;

result += BASE64_ALPHABET.charAt(byte1 >> 2);
result += BASE64_ALPHABET.charAt(((byte1 & 0x03) << 4) | (byte2 >> 4));
result +=
remaining > 1
? BASE64_ALPHABET.charAt(((byte2 & 0x0f) << 2) | (byte3 >> 6))
: "=";
result += remaining > 2 ? BASE64_ALPHABET.charAt(byte3 & 0x3f) : "=";
}

return result;
};

/**
* According to React Native's FormData implementation:
* "a "blob", which in React Native just means an object with a uri attribute"
* @see https://github.com/facebook/react-native/blob/030663bb0634fc76f811cdc63e4d09e7ca32f3d4/packages/react-native/Libraries/Network/FormData.js#L78C1-L82C48
*
* React Native 0.74 File defines `name`/`type` as getter-only, so assigning
* those onto the input File can throw. Return a separate wrapper with own
* `uri`/`type`/`name` whose prototype is the original file (preserving size,
* bytes, and methods).
*/
const wrapRNFormDataFile = (
file: File,
properties: { uri: string; type: string; name: string },
): File => Object.setPrototypeOf({ ...properties }, file) as File;

export const toRNFormDataFile = async (file: File): Promise<File> => {
const type = file.type || "application/octet-stream";
const name = file.name || "upload";
const fileWithUri = file as File & { uri?: unknown };

if (typeof fileWithUri.uri === "string") {
return wrapRNFormDataFile(file, {
uri: fileWithUri.uri,
type,
name,
});
}

const cacheDirectory = FileSystem.cacheDirectory;
if (!cacheDirectory) {
throw new Error("Expo FileSystem cache directory is unavailable");
}

// Empty path segments should fall back, so `||` is intentional over `??`.
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const basename = name.split(/[\\/]/).pop() || "upload";
const uri = `${cacheDirectory}${Date.now()}-${Math.random()}-${basename}`;
await FileSystem.writeAsStringAsync(
uri,
arrayBufferToBase64(await file.arrayBuffer()),
{ encoding: FileSystem.EncodingType.Base64 },
);
Comment on lines +69 to +74

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Generated cache files remain

Each URI-less upload writes a complete copy to a unique cache path, but no success, failure, or abort path removes it, so repeated direct uploads continually consume application cache storage until the operating system evicts the files or later writes fail.

Knowledge Base Used: Expo SDK

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/expo/src/rn-formdata.ts
Line: 64-69

Comment:
**Generated cache files remain**

Each URI-less upload writes a complete copy to a unique cache path, but no success, failure, or abort path removes it, so repeated direct uploads continually consume application cache storage until the operating system evicts the files or later writes fail.

**Knowledge Base Used:** [Expo SDK](https://app.greptile.com/t3/-/custom-context/knowledge-base/pingdotgg/uploadthing/-/docs/expo-sdk.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping for now — OS cache eviction covers these unique paths, and wiring delete-on-success/abort through FormData upload lifecycle is a larger change than this PR. Happy to follow up in a dedicated issue if maintainers want it.


return wrapRNFormDataFile(file, { uri, type, name });
};
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading