Skip to content

Commit 7a40bbd

Browse files
authored
Rewrote fileToUint8Array function to be also NodeJS/Deno compatible. (#2117)
## Motivation for the change, related issues Performing multipart upload and posting of data currently works on the web (client) side. Doing it on PHP WASM instance running on NodeJS or other server runtimes (except Deno) causes this issue due to [FileReader not supported on the runtime](https://developer.mozilla.org/en-US/docs/Web/API/FileReader#browser_compatibility): ``` ReferenceError: FileReader is not defined at file:///c/Users/alonbuella/Documents/projects/php-wasm-vercel/node_modules/@php-wasm/universal/index.js:1717:15 at new Promise (<anonymous>) at fileToUint8Array (file:///c/Users/alonbuella/Documents/projects/php-wasm-vercel/node_modules/@php-wasm/universal/index.js:1716:10) at encodeAsMultipart (file:///c/Users/alonbuella/Documents/projects/php-wasm-vercel/node_modules/@php-wasm/universal/index.js:1702:38) at PHPRequestHandler.ce (file:///c/Users/alonbuella/Documents/projects/php-wasm-vercel/node_modules/@php-wasm/universal/index.js:2070:48) at PHPRequestHandler.le (file:///c/Users/alonbuella/Documents/projects/php-wasm-vercel/node_modules/@php-wasm/universal/index.js:2056:33) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) ``` ## Implementation details This PR introduces an alternative to using FileReader in order to determine the `Uint8Array` value for a `File` instance. This is creating a new instance of `Uint8Array` from the file's buffer instead. `File`'s [arrayBuffer](https://developer.mozilla.org/en-US/docs/Web/API/Blob/arrayBuffer#browser_compatibility) instance method and [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array#browser_compatibility) class are both supported on NodeJS and Deno, and as well as on most recent browsers. ## Testing Instructions (or ideally a Blueprint) - Tested locally via `npm run test` - CI
1 parent 4c2964a commit 7a40bbd

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

packages/php-wasm/universal/src/lib/encode-as-multipart.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,9 @@ export async function encodeAsMultipart(
4747
}
4848

4949
function fileToUint8Array(file: File): Promise<Uint8Array> {
50-
return new Promise((resolve) => {
51-
const reader = new FileReader();
52-
reader.onload = () => {
53-
resolve(new Uint8Array(reader.result as ArrayBuffer));
54-
};
55-
reader.readAsArrayBuffer(file);
56-
});
50+
/**
51+
* @mbuella: Use File.arrayBuffer() to get a Uint8Array from a file, avoiding FileReader
52+
* which is browser-specific. This method is supported in major browsers and NodeJS/Deno runtimes.
53+
*/
54+
return file.arrayBuffer().then((fileBuffer) => new Uint8Array(fileBuffer));
5755
}

0 commit comments

Comments
 (0)