0

I have an extremely large JSON string that I need to send to my server. I encountered payloadTooLargeError when I tried sending the JSON string directly.

So, I decided to send it as a blob instead. But unfortunately, after creating the blob, the blob is returning an empty string.

Here is how I created the blob:

 let largeContentPayload = {
        data: {
            'batch_id': batchId,
            content: extremelyLargeJSON
        }
    };
    const largeContentStringified = JSON.stringify(largeContentPayload);
    const largeContentBlob = new Blob([largeContentStringified], {
        type: 'application/json;charset=utf-8'
    });
    console.log(largeContentBlob); //This is only returning size and type, the JSON string is not there
    const blobUrl = URL.createObjectURL(largeContentBlob);
    let requestBody = new FormData();
    let blob = await fetch(blobUrl).then(r => r.blob());
   

How can this be resolved?

ololo
  • 1,326
  • 2
  • 14
  • 47
  • 1
    Are you in charge of the server? You may wanna set the payload size higher to fit your needs. – Silvan Bregy Feb 17 '22 at 07:11
  • Note that you may also face https://stackoverflow.com/questions/61271613/chrome-filereader-api-event-target-result – Kaiido Feb 17 '22 at 07:17
  • 1
    @SilvanBregy Yes, I am in charge of the server. However, I do not want to explicitly set all the limit settings they suggested in my server. I would rather want to do it well coz I feel that on the occasion the limit is exceeded, the issue might come up again. So, I decided to always send it as a file. – ololo Feb 17 '22 at 07:22
  • Unrelated, but in your code what's the purpose of the lines `const blobUrl = ...` and below? To send that data to the server you don't need the blob URI and even less to fetch it again, this only creates a copy of the Blob's data in memory. (data that is immutable btw, so there is really no point at all to do this) – Kaiido Feb 17 '22 at 07:33

1 Answers1

1

By default if you try to log a blob object in the console it will only display the size and type of that blob.

If you want to see the text content of the blob, you can use text method in the blob.

Reference

Example

async function createBlob() {
  const obj = { hello: 'world' };
  const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' });
  console.log(blob);
  const text = await (new Response(blob)).text();
  console.log(text);
}
createBlob();
Nitheesh
  • 19,238
  • 3
  • 22
  • 49