概述
效果图
- 在所有平台增加Plugin.Media NutGet包
- 编写xaml
<StackLayout>
<Button Text="上传图片" Clicked="Button_Clicked" />
</StackLayout>
3.处理事件
- 编写xaml
private async void Button_Clicked(object sender, EventArgs e)
{
string imgName= await TakeImageAction("123");
}
4.编写TakeImageAction()方法
string action = await DisplayActionSheet("", "", "", "拍照", "从相册选择");
MediaFile pickFile = null;
switch (action)
{
case "拍照":
//判断能否使用摄像头
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("错误提示", "未找到可用摄像头", "确认");
}
var filea = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
//拍照后的文件夹名
Directory = "SjBIdrPics",
//拍照后的文件名
Name = "SjBIdr.jpg"
});
if (filea == null)
return null;
pickFile = filea;
break;
case "从相册选择":
//判断能否读取图片
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("错误提示", "未获得权限读取相册", "确认");
}
//选择图片
var fileb = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (fileb == null)
return null;
pickFile = fileb;
break;
}
if (pickFile != null)
{
//上传图片到服务器
HttpClient client = new HttpClient();
#region
MultipartFormDataContent form = new MultipartFormDataContent();
StreamContent fileContent = new StreamContent(pickFile.GetStream());
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
fileContent.Headers.ContentDisposition.FileName = System.DateTime.Now.ToString("yyyMMddHHmmss") + "_" + UserName + ".jpg";
form.Add(fileContent);
#endregion
HttpResponseMessage res = await client.PostAsync("***/Test/ImageUpload", form);
var uploadModel = await res.Content.ReadAsStringAsync();
return uploadModel;
}
else
{
return "";
}
GitHub官方文档:https://github.com/jamesmontemagno/MediaPlugin
最后
以上就是寒冷鸵鸟为你收集整理的Xamarin.Forms——上传图片的全部内容,希望文章能够帮你解决Xamarin.Forms——上传图片所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复