I am developing a new web application that enables users to upload large file to the server. This is not a production grade app. I am using blazor server side mode for this and I can't figure out a way to show the uploaded percentage to the user. Any ideas or suggestions are highly appreciated.
I am using an InputFile to select the file from the browser. This is a server code.
string safeFileName = WebUtility.HtmlEncode(file.Name);
var path = Path.Combine(env.ContentRootPath, "files", safeFileName);
await using FileStream fs = new(path, FileMode.Create);
await file.OpenReadStream(maxFileSize).CopyToAsync(fs);
This is how I did it. I am calculating a percentage in a loop and manually coping the bytes from one stream to the other stream.
string safeFileName = WebUtility.HtmlEncode(file.Name);
long size = file.Size;
// Save file locally
var path = Path.Combine(env.ContentRootPath, "files", safeFileName);
await using FileStream fs = new(path, FileMode.Create);
var inputstream = file.OpenReadStream(maxFileSize);
await file.OpenReadStream(maxFileSize).CopyToAsync(fs);
byte[] buffer = new byte[bufferSize];
int bytesRead;
long readAmount = 0;
do
{
Array.Clear(buffer);
bytesRead = await inputstream.ReadAsync(buffer, 0, bufferSize);
await fs.WriteAsync(buffer, 0, bytesRead);
readAmount += bytesRead;
percentage = readAmount * 100 / size;
StateHasChanged();
System.Diagnostics.Debug.WriteLine(percentage);
} while (bytesRead > 0);