Worker FormData get File instance

I am uploading a file to a worker using the following code:

const formData = new FormData();
fomData.append('file', file); // File instance from input[type=file].files[0]
console.log(formData.get('file') // Prints File { name, type } in the browser
fetch('worker/upload', { method: 'POST', body: formData };

On the worker side:

const formData = await request.formData();
const file = formData.get('file');
typeof file // Prints "string", not "object" - is not a File instance, but a string of the file content

Can File instance be recovered on the worker end? I’m have verified that sending only the File instance in the fetch body and receiving it in the worker using await request.arrayBuffer() works (returns Uint8Array or something, not a string), but that way I lose information such as the file name and MIME type. I want to preserve this and FormData would be ideal for this, but not if it can’t give me back at least a Blob, not a string, which will likely corrupt on a bad file and is being printed as readable in web KV view unlike proper ArrayBuffer which prompts me to download it.

One more thing which I’ve just realized is that without the ability to get a File instance out of the FormData, it is impossible to upload multiple files into a worker (using multipart encoding) unless the worker author parses the multipart request body themselves.

I’ve resorted to parsing the MIME mutlipart blob myself in order to gain access to the file contents in a binary form as well as the metadata (name and type).

I really hope a solution pops up where FormData could be made to work as described in my original post.

1 Like