2

對不起,我的英語。我有一個將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); 
     } 
    } 

可否更改代碼收到關於在回調函數下載文件的進度?

回答

0

在Windows Runtime上,您可以嘗試切換到Windows.Web.HttpClient類。其PostAsync方法返回IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>接口。此界面有Progress事件,您可以在等待結果前簡單訂閱該事件。

+0

感謝您的回答!問題是,當你使用'Windows.Web.Http.HttpClient'時,服務器收到無效響應。所以我有時使用'Windows.Net.Http.HttpClient' – Georgy

+0

如果你想使用'System.Net.Http.HttpClient',那麼你需要實現你自己的'HttpMessageHandler',它將封裝進度邏輯,並可以傳遞給' HttpClient'構造函數。 – Alex