2016-02-29 59 views
0

我目前使用Windows手機應用程序來點擊圖片,並且我想使用HTTP發佈請求將該圖片上傳到網絡服務。我不想使用Windows Phone Silverlight。如何將jpeg圖像轉換爲字節格式

如何將該圖像發送到Web服務URL?

回答

3

在http上發佈圖像就像發佈任何其他文件類型一樣。使用下面的代碼片段

public string PostFileUsingApi() 
{ 
    string result = ""; 
    string param1 = "value1"; 

    using (var handler = new HttpClientHandler()) { 
     using (var client = new HttpClient(handler) { BaseAddress = new Uri("http://localhost:8008") }) { 
      client.Timeout = new TimeSpan(0, 20, 0); 

      StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); 
      Stream stream = await storageFile.OpenStreamForReadAsync(); 

      var requestContent = new MultipartFormDataContent(); 
      StreamContent fileContent = new StreamContent(stream); 
      fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { 
       Name = "imagekey", //content key goes here 
       FileName = "myimage" 
      }; 

      fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/bmp"); 

      requestContent.Add(fileContent); 

      client.DefaultRequestHeaders.Add("ClientSecretKey", "ClientSecretValue"); 

      HttpResponseMessage response = await client.PostAsync("api/controller/UploadData?param1=" + HttpUtility.UrlEncode(param1), requestContent).Result; 

      if (response.StatusCode == System.Net.HttpStatusCode.OK) { 
       result = await response.Content.ReadAsStringAsync().Result 
      } else { 
       result = ""; 
      } 
     } 
    } 

    return result; 
} 

安裝這個包來解決依賴性 https://www.nuget.org/packages/microsoft.aspnet.webapi.client/

+0

但沒有FILESTREAM爲以system.IO – chinna2580

+0

我已經編輯代碼尖晶石工作,甚至我已經添加的Windows Phone 8應用程序集引用與Windows手機流。在沙箱環境中,您無法使用IO Stream訪問文件,您需要從Windows Phone中的StorageFile對象獲取流。 – Zain

+0

@Zain與'Async'一起使用'await'方法 – Eldho

相關問題