UWP 使用Windows.Web.Http命名空間下的HttpClient使用post方法,上傳圖片服務器

1.從相冊裏面選取圖片web

 1         /// <summary>
 2         /// 1.1 從相冊裏面選取圖片
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private async void btnPhoto_Click(object sender, RoutedEventArgs e)
 7         {
 8             //建立和自定義 FileOpenPicker (從本地獲取一張圖片) 
 9             FileOpenPicker picker = new FileOpenPicker();
10             picker.ViewMode = PickerViewMode.Thumbnail; //可經過使用圖片縮略圖建立豐富的視覺顯示,以顯示文件選取器中的文件  
11             picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;//對話框打開時的默認路徑(圖片庫)
12             //設置可選擇的文件類型
13             picker.FileTypeFilter.Add(".jpg");
14             picker.FileTypeFilter.Add(".jpeg");
15             picker.FileTypeFilter.Add(".png");
16             picker.FileTypeFilter.Add(".gif");
17             //選取單個文件  
18             StorageFile file = await picker.PickSingleFileAsync();
19             if (file != null)
20             {
21                 CutPicture(file);//裁剪圖片
22             }
23         }

2.從相機裏面選取圖片windows

 1         /// <summary>
 2         /// 1.2 相機
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private async void btnCamera_Click(object sender, RoutedEventArgs e)
 7         {
 8             CameraCaptureUI captureUI = new CameraCaptureUI();
 9             captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;//注意:這裏只設置了返回圖片格式:Jpeg若是是:Png(手機能夠顯示,在覈心後臺圖片不顯示)和JpegXR(都不顯示)會報錯;;根據實際狀況來
10             captureUI.PhotoSettings.AllowCropping = false;
11             StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
12             if (photo != null)
13             {
14                 CutPicture(photo);//裁剪圖片
15             }
16         }

3.裁剪圖片調用的公共方法CutPicture服務器

 1         /// <summary>
 2         /// 1.4 裁剪圖片
 3         /// </summary>
 4         /// <param name="file"></param>
 5         public async void CutPicture(StorageFile file)
 6         {
 7             #region 裁剪圖片
 8             var inputFile = SharedStorageAccessManager.AddFile(file);//  獲取一個文件共享Token,使應用程序可以與另外一個應用程序共享指定的文件。
 9             var destination = await ApplicationData.Current.LocalFolder.CreateFileAsync("Cropped.jpg", CreationCollisionOption.ReplaceExisting);//在應用文件夾中創建文件用來存儲裁剪後的圖像 
10             var destinationFile = SharedStorageAccessManager.AddFile(destination);
11             var options = new LauncherOptions();
12             options.TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe";//應用於啓動文件或URI的目標包的包名稱
13             //待會要傳入的參數 
14             var parameters = new ValueSet();
15             parameters.Add("InputToken", inputFile);                //輸入文件 
16             parameters.Add("DestinationToken", destinationFile);    //輸出文件 
17             parameters.Add("ShowCamera", false);                    //它容許咱們顯示一個按鈕,以容許用戶採起當場圖象(可是好像並無什麼用) 
18             parameters.Add("EllipticalCrop", true);                 //截圖區域顯示爲圓(最後截出來仍是方形) 
19             parameters.Add("CropWidthPixals", 300);
20             parameters.Add("CropHeightPixals", 300);
21             //調用系統自帶截圖並返回結果 
22             var result = await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), options, parameters);
23             if (result.Status == LaunchUriStatus.Success && result.Result != null)
24             {
25                 //對裁剪後圖像的下一步處理 
26                 try
27                 {
28                     // 載入已保存的裁剪後圖片 
29                     var stream = await destination.OpenReadAsync();
30                     var bitmap = new BitmapImage();
31                     await bitmap.SetSourceAsync(stream);
32                       // 顯示裁剪事後的圖片 
33                     imglogo.ImageSource = bitmap;
34                     //此方法是請求後臺修改圖片
35                     SetHeadPicture(destination);
36                     OutBorder.Visibility = Visibility.Collapsed;
37                 }
38                 catch (Exception ex)
39                 {
40                     System.Diagnostics.Debug.WriteLine(ex.Message + ex.StackTrace);
41                 }
42             }
43             #endregion
44         }

 4.使用Windows.Web.Http命名空間下的HttpClient使用post方法,上傳圖片服務器app

參考:https://social.msdn.microsoft.com/Forums/zh-CN/ec0ffd44-f7a6-4a53-8f8e-d15e13cfa5fb/windowswebhttphttpclientpost?forum=winstoreappzhcnasync

個人作法是將須要上傳的參數放在HttpMultipartFormDataContent中,而後再使用HttpClient的PostAsync進行提交post

請求參數:url

 1       
 2        /// <summary>
 3         /// 向服務器發送post請求(修改頭像)
 4         /// </summary>
 5         /// <param name="url">路徑</param>
 6         /// <returns></returns>
 7         public async static Task<string> SendPostRequest(string url)
 8         {
 9             try
10             {
11                 Dictionary<string, object> dic = new Dictionary<string, object>();
12                 dic.Add("GWnumber", setHeadPicture.GWnumber);
13                 dic.Add("token", setHeadPicture.Token);
14                 dic.Add("file", setHeadPicture.File);//file值是StorageFile類型
15                 dic.Add("systemType", setHeadPicture.SystemType);
16 
17                 HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
18                 foreach (KeyValuePair<string, object> item in dic)
19                 {
20                     if (item.Key == "file")
21                     {
22                         StorageFile file = item.Value as StorageFile;
23                         HttpStreamContent streamContent = new HttpStreamContent(await file.OpenReadAsync());
24                         form.Add(streamContent, item.Key, "file.jpg");//注意:這裏的值是必須的,圖片因此使用的是HttpStreamContent
25                     }
26                     else
27                     {
28                         form.Add(new HttpStringContent(item.Value + ""), item.Key);
29                     }
30                 }
31                 HttpClient httpClient = new HttpClient();
32                 HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), form).AsTask();
33                 var contentType = response.Content.Headers.ContentType;
34                 if (string.IsNullOrEmpty(contentType.CharSet))
35                 {
36                     contentType.CharSet = "utf-8";
37                 }
38                 return await response.Content.ReadAsStringAsync();
39 
40             }
41             catch (Exception ex)
42             {
43                 throw ;
44             }
45         }

uwp小白,請多指教!!spa

相關文章
相關標籤/搜索