Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download PDF from big base64 string with JavaScript and Blazor?

In Blazor WASM I have this code:

protected async Task Download()
    {
        base64Data = await Http.GetByteArrayAsync(url);
        await jsRunTime.InvokeVoidAsync("downloadFile", "application/pdf", base64Data, "test.pdf");
    }

And in the JavaScript file I have this:

function downloadFile(contentType, base64Data, fileName) {
    const linkSource = `data:${contentType};base64,${base64Data}`;
    const downloadLink = document.createElement("a");
    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
}

If I try to get a really small pdf it works, but if the base64 string is too large (a file with over 400kB), I have a network failure when downloading the file. A strange thing is on Edge network tab, at Fetch/XHR, don't matter the file I try to download, the size is always 576kB.

Any idea of what to do? Thanks!

like image 922
Diego Avatar asked Sep 06 '25 03:09

Diego


1 Answers

I finally made it work.

I had to use GetStringAsync and Trim the server response because the base64 string was surrounded by quotation marks.

protected async Task Download()
{
base64Data = await Http.GetStringAsync(url);         
base64Data = base64Data.Trim('"');
await jsRunTime.InvokeVoidAsync("downloadFile", "application/pdf", base64Data, "test.pdf");
}

Thanks guys!

like image 105
Diego Avatar answered Sep 08 '25 22:09

Diego