1

In my worker I am converting a base64 string I get from the request to a blob with some function. However, when I try to PUT the blob into my bucket, I get "Network Connection Lost" error. I can successfully PUT just the base64 string or any other string but not a blob. Here is my worker:

// Function to convert b64 to blob (working fine)
function b64toBlob(b64Data, contentType, sliceSize=512) {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const key = url.pathname.slice(1);

    switch (request.method) {
      case 'PUT':
        const contentType = 'application/pdf';
        const b64Data = request.body;
        
        const blob = b64toBlob(b64Data, contentType);

        try {
          await env.qa_sub_agreements_bucket.put(key, blob, { // Failing here
            httpMetadata: request.headers,
          })
          return new Response(blob) // Successfully returns the blob when above PUT is commented out
        } catch (e) {
          console.error(e.message, e.stack); // Logs out "Error: Network Connection Lost"
        }
brandon
  • 21
  • 3

1 Answers1

0

Hard to say definitively because the Worker posted doesn't appear to be totally complete. An eagle-eyed coworker spotted that it looks like the problem may be that you're invoking atob on a ReadableStream and likely that conversion is what's throwing the exception.

Vitali
  • 3,411
  • 2
  • 24
  • 25
  • To clarify what Vitali is saying, your code appears to take `request.body`, which is a `ReadableStream` object, and pass that into `atob()` as if it were a string. If you wanted to decode the text of the request, you need to do `await request.text()`. That said, this problem doesn't seem to match your description. Is the code you pasted the actual full code that produced the error? – Kenton Varda Sep 09 '22 at 01:08
  • Thanks for the reply I'll give that a shot. The rest of the code is just the other GET and DELETE methods, I cut those out to shorten the post. I'm using Postman to hit the endpoint so maybe that could be producing an issue? @KentonVarda – brandon Sep 11 '22 at 08:07