我需要一些关于奇怪 WebClient.UploadFileAsync() 行为的帮助。我正在使用 POST 方法将文件上传到远程 HTTP 服务器(nginx)。POST 通过 PHP 脚本(地址指代)进行处理。
我有这个简单的代码
public void uploadFile(string filePath)
{
webClient = new WebClient();
webClient.Credentials = new NetworkCredential(Constant.HTTPUsername,Constant.HTTPPassword);
webClient.Headers.Add("Test", TestKey);
webClient.UploadProgressChanged += webClient_UploadProgressChanged;
webClient.UploadFileCompleted += webClient_UploadFileCompleted;
try
{
webClient.UploadFileAsync(new Uri(Address), "POST", filePath);
}
catch (Exception error)
{
throw new CustomException(error.Message);
}
}
在 UploadProgressChanged 中,我只需使用给定的 ProgressPercentage 更新 progressBar。第一个问题是报告的进度百分比,任何文件大小都是:
[17.38.14] Progress: 0 Bytes Sent: 175 / 269264
[17.38.14] Progress: 1 Bytes Sent: 8367 / 269264
[17.38.14] Progress: 3 Bytes Sent: 16559 / 269264
[17.38.14] Progress: 4 Bytes Sent: 24751 / 269264
[17.38.14] Progress: 6 Bytes Sent: 32943 / 269264
[17.38.14] Progress: 7 Bytes Sent: 41135 / 269264
[17.38.14] Progress: 9 Bytes Sent: 49327 / 269264
[17.38.14] Progress: 10 Bytes Sent: 57519 / 269264
[17.38.14] Progress: 12 Bytes Sent: 65711 / 269264
[17.38.14] Progress: 13 Bytes Sent: 73903 / 269264
[17.38.14] Progress: 15 Bytes Sent: 82095 / 269264
[17.38.14] Progress: 16 Bytes Sent: 90287 / 269264
[17.38.14] Progress: 18 Bytes Sent: 98479 / 269264
[17.38.15] Progress: 19 Bytes Sent: 106671 / 269264
[17.38.15] Progress: 21 Bytes Sent: 114863 / 269264
[17.38.15] Progress: 22 Bytes Sent: 123055 / 269264
[17.38.15] Progress: 24 Bytes Sent: 131247 / 269264
[17.38.15] Progress: 25 Bytes Sent: 139439 / 269264
[17.38.15] Progress: 27 Bytes Sent: 147631 / 269264
[17.38.16] Progress: 28 Bytes Sent: 155823 / 269264
[17.38.16] Progress: 30 Bytes Sent: 164015 / 269264
[17.38.16] Progress: 31 Bytes Sent: 172207 / 269264
[17.38.16] Progress: 33 Bytes Sent: 180399 / 269264
[17.38.16] Progress: 35 Bytes Sent: 188591 / 269264
[17.38.16] Progress: 36 Bytes Sent: 196783 / 269264
[17.38.17] Progress: 38 Bytes Sent: 204975 / 269264
[17.38.17] Progress: 39 Bytes Sent: 213167 / 269264
[17.38.17] Progress: 41 Bytes Sent: 221359 / 269264
[17.38.17] Progress: 42 Bytes Sent: 229551 / 269264
[17.38.17] Progress: 44 Bytes Sent: 237743 / 269264
[17.38.17] Progress: 45 Bytes Sent: 245935 / 269264
[17.38.17] Progress: 47 Bytes Sent: 254127 / 269264
[17.38.18] Progress: 48 Bytes Sent: 262319 / 269264
[17.38.18] Progress: 49 Bytes Sent: 269220 / 269264
[17.38.18] Progress: 50 Bytes Sent: 269264 / 269264
[17.38.25] Progress: -50 Bytes Sent: 269264 / 269264
[17.38.25] Progress: 100 Bytes Sent: 269264 / 269264
[17.38.25] FileCompleted event raised!
所以,在网上搜索,我发现从 50->100 的跳跃只是百分比报告中的一个设计选择......所以我很好。奇怪的问题是,即使在 50%(发送整个文件时),网络接口仍然会产生流量并且仍在上传。事实上,从上面日志中的时间可以看出,文件发送后需要 7 秒才能引发 UploadFileCompletedEvent..事实上,与此同时,我仍然通过 HTTP 发送文件。
这里的问题是我无法可靠地更新我的 UI:进度条会增长到 50%,但随后会卡住等待上传完成(这是一种不好的行为,因为对于大文件,这个时间会显着增长)。
问题是:如何可靠地让用户了解文件上传进度?
谢谢。
PS该方法工作得很好,文件已正确上传到远程服务器。唯一的问题是进度报告。