如何获取上传进度

本文关键字:获取 何获取 | 更新日期: 2023-09-27 18:31:00

对不起我的英语。我有一个将存储文件发送到服务器的方法。我尝试使用Windows.Web.Http.HttpClient,但不起作用(从服务器获得无效响应),所以我使用System.Net.Http.HttpClient
这是我的代码:

    public static async void Upload(string uri, StorageFile data, Action<double> progressCallback = null)
    {
        try
        {
            byte[] fileBytes =await ReadFile(data);
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            MultipartContent content = new System.Net.Http.MultipartFormDataContent();
            var file1 = new ByteArrayContent(fileBytes);
            file1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "file1",
                FileName = data.Name,
            };
            content.Add(file1);
            System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, content);
            response.EnsureSuccessStatusCode();
            var raw_response = await response.Content.ReadAsByteArrayAsync();
            var r2 = Encoding.UTF8.GetString(raw_response, 0, raw_response.Length);
            if (r2[0] == ''uFEFF')
            {
                r2 = r2.Substring(1);
            }
            Logger.Info(r2);
        }
        catch (Exception exc)
        {
            Logger.Error( exc);
        }
    }

是否可以更改代码以接收有关在回调函数中下载文件的进度?

如何获取上传进度

在 Windows 运行时上,您可以尝试切换到Windows.Web.HttpClient类。它的PostAsync方法返回IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>接口。此接口具有Progress事件,您可以在等待结果之前简单地订阅该事件。

上传

进度文件的最简单方法

我遇到了同样的问题,经过一些尝试,发现您可以通过跟踪要上传的文件的FileStream Position轻松获得字节准确的进度。

这是一个示例代码,显示了这一点。

FileStream fileToUpload = File.OpenRead(@"C:'test.mp3");
HttpContent content = new StreamContent(fileToUpload);
HttpRequestMessage msg = new HttpRequestMessage{
    Content=content,
    RequestUri = new Uri(--yourUploadURL--)
}
bool keepTracking = true; //to start and stop the tracking thread
new Task(new Action(() => { progressTracker(fileToUpload, ref keepTracking); })).Start();
var result = httpClient.SendAsync(msg).Result;
keepTracking = false; //stops the tracking thread

并将progressTracker()定义为

void progressTracker(FileStream streamToTrack, ref bool keepTracking)
{
    int prevPos = -1;
    while (keepTracking)
    {
        int pos = (int)Math.Round(100 * (streamToTrack.Position / (double)streamToTrack.Length));
        if (pos != prevPos)
        {
            Console.WriteLine(pos + "%");
        }
        prevPos = pos;
        Thread.Sleep(100); //only update progress every 100ms
    }
}

这解决了我的问题。