[英]Tracking HttpClient.PostAsync progress using Blazor and Aspnet Webapi
I am currently using Blazor and Asp.Net WebApi Controller to perform some file upload/download..And I have a UploadFiles() called in the Blazor client that looks like this:我目前正在使用 Blazor 和 Asp.Net WebApi Controller 来执行一些文件上传/下载。我有一个在 Blazor 客户端中调用的 UploadFiles() ,如下所示:
public async Task<bool> UploadFiles(Action<int> callback, IReadOnlyList<IBrowserFile> files, string subdir = "")
{
if (files != null)
{
var content = new MultipartFormDataContent();
foreach (var file in files)
{
var fileContent = new StreamContent(file.OpenReadStream(_allowedMaxFileSize));
content.Add(fileContent, "\"files\"", file.Name);
hasItemsForUpload = true;
}
if (content != null)
{
var uri = $@"api/mycontroller/upload?subdir=" + subdir;
var result = await _http.PostAsync(uri, content);
if (result.IsSuccessStatusCode)
{
return true;
}
}
}
return false;
}
Is there a way for me to easily track httpclient.postasync() % progress where I can pass the % as int in my callback?有没有办法让我轻松跟踪 httpclient.postasync() % 进度,我可以在我的回调中将 % 作为 int 传递? Note that _http
here is injected through dependency injection registered as AddScope() of the startup.cs注意这里的_http是通过注册为startup.cs的_http
()的依赖注入注入的
I've seen complicated examples using custom http content but I can't seem to wrap my head around it... :(我见过使用自定义 http 内容的复杂示例,但我似乎无法理解它...:(
Please help..请帮忙..
FileComponent.razor FileComponent.razor
<div> Progress: @current </div>
@code
{
int current = 0;
void UpdateProgress()
{
current++;
StateHasChanged();
}
void ResetBatch(){ current=0; }
public async Task<bool> UploadFiles(Action<int> callback, IReadOnlyList<IBrowserFile> files, string subdir = "")
{
ResetBatch();
if (files != null)
{
var content = new MultipartFormDataContent();
foreach (var file in files)
{
var fileContent = new StreamContent(file.OpenReadStream(_allowedMaxFileSize));
content.Add(fileContent, "\"files\"", file.Name);
hasItemsForUpload = true;
if (content != null)
{
var uri = $@"api/mycontroller/upload?subdir=" + subdir;
var result = await _http.PostAsync(uri, content);
}
UpdateProgress();
}
}
ResetBatch();
return true;
}
}
Note that instead of 'current' you can create a whole upload batch class that contains information regarding total files to be updated, filenames, current file name, status of each upload etc etc.请注意,您可以创建一个完整的上传批次 class 而不是“当前”,其中包含有关要更新的文件总数、文件名、当前文件名、每个上传状态等的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.