Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert async AsyncIterable<Uint8Array> to File in Javascript

Hello I'm sending/POST a File from a HTML Form on a browser client to a Remix application server.

The Remix applicaton server is sending/handling my File as a async AsyncIterable. I now need to convert it back to a File object so I can send it to a backend server as FormData.

I tried both with and without buffer for demo:

Does anyone have experiance with convert AsyncIterable to Blob then to File??

const myHandler: UploadHandler = async ({ name, contentType, data, filename }) => {
  //'data' is data of type AsyncIterable<Uint8Array>
  //'contentType' is 'image/png'

  let dataArray1 = []; //test1 without buffer
  let dataArray2 = []; //test2 with buffer

  for await (const x of data) {
    dataArray1.push(x); //without buffer
    dataArray2.push(x.buffer); //with buffer
  }

  const blob1 = new Blob(dataArray1, {type: contentType});
  const blob2 = new Blob(dataArray2, {type: contentType});

  const file1 = new File([blob1], filename, { type: contentType });
  const file2 = new File([blob2], filename, { type: contentType });
  console.log('file1.size: ', file1.size); 
  //file1 size is 1336843 (and for file2)
  //but i'm getting content-length 1337028 from my browser Form
  //so I'm not sure if it's correct

  return file1;
};

[![content-length size][1]][1]

[![enter image description here][2]][2]

[![enter image description here][3]][3]

[![enter image description here][4]][4]

enter image description here

like image 750
Bobby Avatar asked Mar 29 '26 18:03

Bobby


1 Answers

Try passing the blob parts directly into the file constructor.

const myHandler: UploadHandler = async ({ name, contentType, data, filename }) =>
{
   const dataArray1 = [];

   for await (const x of data)
   {
      dataArray1.push(x);
   }

   const file1 = new File(dataArray1, filename, { type: contentType });

   return file1;
};
like image 121
Sergio Carneiro Avatar answered Mar 31 '26 10:03

Sergio Carneiro