如何获得上传进度?

时间:2016-01-18 13:27:37

标签: c# windows-runtime windows-phone-8.1 windows-8.1 winrt-httpclient

抱歉我的英文。我有一个方法,我将StorageFile发送到服务器。我尝试使用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);
        }
    }

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

上传文件的最简单方法

我遇到了同样的问题,经过多次尝试后发现,您可以通过跟踪要上传的文件的 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
    }
}

这解决了我的问题。