1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { string serverUrl = "https://localhost:7252/"; string requestUrl = "api/File/DownloadFile"; string savePath = @"D:\1.png";
var vParameters = new Dictionary<string, object> { { "FileName", "1.png" } }; var vDownload = await HttpClientHelper.DownloadGetAsync(new Uri(serverUrl), requestUrl, vParameters, savePath, DownloadProgressChanged); MessageBox.Show($"保存{(vDownload ? "成功" : "失败")}"); }
private void DownloadProgressChanged(object? arg1, HttpProgressEventArgs arg2) { this.Dispatcher.Invoke(new Action(() => { if (arg2.ProgressPercentage >= 0 && arg2.ProgressPercentage <= 100) { progressBar.Value = arg2.ProgressPercentage / 100.0; number.Content = $"{ByteChange(arg2.BytesTransferred)}/{ByteChange(arg2.TotalBytes)}"; CalcDownloadSpeed(DateTime.Now, arg2.BytesTransferred); } })); }
private DateTime lastTime = DateTime.Now; private long BytesTransferred = 0;
private void CalcDownloadSpeed(DateTime time, long bytesTransferred) { if (lastTime.Second != time.Second) { this.Dispatcher.Invoke(new Action(() => { number2.Content = $"Speed: {ByteChange(bytesTransferred - BytesTransferred)}/s"; }));
lastTime = time; BytesTransferred = bytesTransferred; } }
private string ByteChange(long? TotalBytes) { long kb = 1024; long mb = kb * kb; long gb = mb * kb; long tb = gb * kb;
if (TotalBytes >= tb) { return $"{Math.Round((decimal)TotalBytes / tb, 2)}TB"; } else if (TotalBytes >= gb) { return $"{Math.Round((decimal)TotalBytes / gb, 2)}GB"; } else if (TotalBytes >= mb) { return $"{Math.Round((decimal)TotalBytes / mb, 2)}MB"; } else if (TotalBytes >= kb) { return $"{Math.Round((decimal)TotalBytes / kb, 2)}KB"; } else { return $"{TotalBytes}B"; } }
|