Error: Network Connection Lost - saving form data (file) to R2 bucket

803 views Asked by At

I have this handler in my worker:

const data = await event.request.formData();

const key = data.get('filename');
const file = data.get('file');

if (typeof key !== 'string' || !file) {
  return res.send(
    { message: 'Post body is not valid.' },
    undefined,
    400
  );
}

await BUCKET.put(key, file);

return new Response(file);

If I comment out the await BUCKET.put(key, file); line, then I get the response of the file as expected. But with that line in the function, I get the error:

Uncaught (in promise) Error: Network connection lost.

I have confirmed that by changing the put to a get, I can retrieve files from that bucket, so there doesn't seem to be a problem with the connection itself.

1

There are 1 answers

2
Vitali On

I just noticed that you're calling formData on the request. This is causing you to read the object into RAM. Workers has a 128 MiB limit so what's likely happening is that you're exceeding that limit (probably egregiously since we do give some buffer) and thus Cloudflare is terminating your Worker.

What you'll want to do is make sure you upload the file raw (not as a form) and access the raw ReadableStream. Alternatively, you can try writing a TransformStream to parse out the payload in a streaming fashion if you're confident the file payload (& any metadata you need) will come after the name. Usually it's easier to change your upload mechanism.