(I am using Blazor Server running .Net 5, Google Chrome)
To be able to save a file and make it available for the user in the browser, via 'downloaded files', I have learned that you need to use some javascript.
To start with, I am from the server side of Blazor preparing a file, which comes from a WebAPi as a FileStream object.
using (MemoryStream ms = new MemoryStream())
{
fsrResponse.Data.FileStream.CopyTo(ms);
byteArray = ms.ToArray();
}
res= await js.SaveAs(fileName, byteArray);
I convert the File Stream to a Byte Array which is then passed to the SaveAs Task, which calls the javascript function after converting the byteArray to a Base64 string.
public static async Task<bool> SaveAs(this IJSRuntime js, string filename, byte[] byteArray)
{
bool ret;
try
{
string bytesBase64 = Convert.ToBase64String(byteArray);
ret = await js.InvokeAsync<bool>("saveAsFile", TimeSpan.FromMinutes(1) ,filename, bytesBase64);
}
catch (Exception ex)
{
string message = ex.Message;
ret = false;
}
return ret;
}
This is the javascript method, which works most of the time.
function saveAsFile(filename, bytesBase64) {
var ret;
try {
var a = document.createElement('a');
a.download = filename;
a.target = '_self';
a.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
ret = true;
} catch (e) {
ret = false;
}
return ret;
}
This workflow works perfectly for files that are smaller than 40-50 MB, but after that, the web site crashes. While debugging this, I can see that everything works until I call this line of code, after that, it stops executing. It doesn't hit the javascript code at all.
ret = await js.InvokeAsync<bool>("saveAsFile", TimeSpan.FromMinutes(1) ,filename, bytesBase64);
I am not sure if this is related to file size directly, or if it is a timeout problem. (it takes around 33-34 seconds when I just checked, before it fails.