Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can implement a server side progress function while uploading a file to the client in ASP.NET Core 7 Web API controller using the following steps:

  1. Add the following NuGet packages to your project:
  • Microsoft.AspNetCore.Http.Features
  • Microsoft.AspNetCore.WebUtilities
  1. In your controller action that handles the file upload, declare an instance of IFormFile and cast the incoming Request.Form.Files parameter to it.

public async Task<iactionresult> UploadFile(IFormFile file)

  1. Get the length of the uploaded file and use it to calculate the percentage of the file that has been uploaded.

var totalBytes = file.Length; var uploadedBytes = 0L;

...

if (chunkedFile.Length > 0) { await fileStream.WriteAsync(chunkedFile, cancellationToken); uploadedBytes += chunkedFile.Length;

// Calculate progress percentage
var progress = Convert.ToInt32((uploadedBytes * 100) / totalBytes);

}

  1. Return the progress value to the client.

return Ok(progress);

  1. On the client side, use AJAX or WebSockets to make periodic requests to the server to get the progress value and update the user interface accordingly.