C# 如何获得上传进度?

C# 如何获得上传进度?,c#,windows-runtime,windows-phone-8.1,windows-8.1,winrt-httpclient,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) {

对不起我的英语。我有一种将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);
        }
    }
publicstaticasynchvoid上传(字符串uri,存储文件数据,Action-progressCallback=null)
{
尝试
{
byte[]fileBytes=等待读取文件(数据);
System.Net.Http.HttpClient client=新系统.Net.Http.HttpClient();
MultipartContent content=new System.Net.Http.MultipartFormDataContent();
var file1=新的ByteArrayContent(fileBytes);
file1.Headers.ContentDisposition=新的ContentDispositionHeaderValue(“表单数据”)
{
Name=“file1”,
FileName=data.Name,
};
内容。添加(文件1);
System.Net.Http.HttpResponseMessage response=wait client.PostAsync(uri,内容);
response.EnsureSuccessStatusCode();
var raw_response=wait response.Content.ReadAsByteArrayAsync();
var r2=Encoding.UTF8.GetString(原始响应,0,原始响应.Length);
如果(r2[0]='\uFEFF')
{
r2=r2.子串(1);
}
记录器信息(r2);
}
捕获(异常exc)
{
记录器错误(exc);
}
}

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

在Windows运行时,您可以尝试切换到类。其方法返回接口。此界面包含事件,您可以在等待结果之前订阅该事件。

谢谢您的回答!问题是,当您使用
Windows.Web.Http.HttpClient
时,我从服务器收到无效响应。因此,我有时被使用
Windows.Net.Http.HttpClient
如果您想使用
System.Net.Http.HttpClient
,那么您需要实现自己的
HttpMessageHandler
,它将封装进度逻辑,并可以传递给
HttpClient
构造函数。