UWP 使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器

时间:2023-03-10 01:38:08
UWP 使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器

1.从相册里面选取图片

         /// <summary>
/// 1.1 从相册里面选取图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btnPhoto_Click(object sender, RoutedEventArgs e)
{
//创建和自定义 FileOpenPicker (从本地获取一张图片)
FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail; //可通过使用图片缩略图创建丰富的视觉显示,以显示文件选取器中的文件
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;//对话框打开时的默认路径(图片库)
//设置可选择的文件类型
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".gif");
//选取单个文件
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
CutPicture(file);//裁剪图片
}
}

2.从相机里面选取图片

         /// <summary>
/// 1.2 相机
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btnCamera_Click(object sender, RoutedEventArgs e)
{
CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;//注意:这里只设置了返回图片格式:Jpeg如果是:Png(手机可以显示,在核心后台图片不显示)和JpegXR(都不显示)会报错;;根据实际情况来
captureUI.PhotoSettings.AllowCropping = false;
StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
CutPicture(photo);//裁剪图片
}
}

3.裁剪图片调用的公共方法CutPicture

UWP 使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器

         /// <summary>
/// 1.4 裁剪图片
/// </summary>
/// <param name="file"></param>
public async void CutPicture(StorageFile file)
{
#region 裁剪图片
var inputFile = SharedStorageAccessManager.AddFile(file);// 获取一个文件共享Token,使应用程序能够与另一个应用程序共享指定的文件。
var destination = await ApplicationData.Current.LocalFolder.CreateFileAsync("Cropped.jpg", CreationCollisionOption.ReplaceExisting);//在应用文件夹中建立文件用来存储裁剪后的图像
var destinationFile = SharedStorageAccessManager.AddFile(destination);
var options = new LauncherOptions();
options.TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe";//应用于启动文件或URI的目标包的包名称
//待会要传入的参数
var parameters = new ValueSet();
parameters.Add("InputToken", inputFile); //输入文件
parameters.Add("DestinationToken", destinationFile); //输出文件
parameters.Add("ShowCamera", false); //它允许我们显示一个按钮,以允许用户采取当场图象(但是好像并没有什么用)
parameters.Add("EllipticalCrop", true); //截图区域显示为圆(最后截出来还是方形)
parameters.Add("CropWidthPixals", );
parameters.Add("CropHeightPixals", );
//调用系统自带截图并返回结果
var result = await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), options, parameters);
if (result.Status == LaunchUriStatus.Success && result.Result != null)
{
//对裁剪后图像的下一步处理
try
{
// 载入已保存的裁剪后图片
var stream = await destination.OpenReadAsync();
var bitmap = new BitmapImage();
await bitmap.SetSourceAsync(stream);
// 显示裁剪过后的图片
imglogo.ImageSource = bitmap;
//此方法是请求后台修改图片
SetHeadPicture(destination);
OutBorder.Visibility = Visibility.Collapsed;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + ex.StackTrace);
}
}
#endregion
}

4.使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器

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

我的做法是将需要上传的参数放在HttpMultipartFormDataContent中,然后再使用HttpClient的PostAsync进行提交

请求参数:

UWP 使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器

        /// <summary>
/// 向服务器发送post请求(修改头像)
/// </summary>
/// <param name="url">路径</param>
/// <returns></returns>
public async static Task<string> SendPostRequest(string url)
{
try
{
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("GWnumber", setHeadPicture.GWnumber);
dic.Add("token", setHeadPicture.Token);
dic.Add("file", setHeadPicture.File);//file值是StorageFile类型
dic.Add("systemType", setHeadPicture.SystemType); HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
foreach (KeyValuePair<string, object> item in dic)
{
if (item.Key == "file")
{
StorageFile file = item.Value as StorageFile;
HttpStreamContent streamContent = new HttpStreamContent(await file.OpenReadAsync());
form.Add(streamContent, item.Key, "file.jpg");//注意:这里的值是必须的,图片所以使用的是HttpStreamContent
}
else
{
form.Add(new HttpStringContent(item.Value + ""), item.Key);
}
}
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), form).AsTask();
var contentType = response.Content.Headers.ContentType;
if (string.IsNullOrEmpty(contentType.CharSet))
{
contentType.CharSet = "utf-8";
}
return await response.Content.ReadAsStringAsync(); }
catch (Exception ex)
{
throw ;
}
}

uwp小白,请多指教!!