[英]Xamarin form - how to upload and retrieve image using sql server web api
我需要將圖像作為二進制數據上傳並在此處檢索,這是我的代碼Web Api
[ResponseType(typeof(tblEmpPicture))]
public IHttpActionResult PosttblEmpPicture(tblEmpPicture tblEmpPicture)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.tblEmpPictures.Add(tblEmpPicture);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (tblEmpPictureExists(tblEmpPicture.intEmpCode))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = tblEmpPicture.intEmpCode }, tblEmpPicture);
}
MainPage.xaml
<Image x:Name="userImage" Source="{Binding Pic.vbrPicture, Mode=TwoWay}" Aspect="AspectFill" WidthRequest="85" HeightRequest="85" >
MainPage.cs
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
if (file == null)
return;
await DisplayAlert("File Location", file.Path, "OK");
userImage.Source = ImageSource.FromStream(() =>file.GetStream());
await ((MainViewModel)this.BindingContext).PutUserPicCommand();
主模型
private tblEmpPicture _Pic = new tblEmpPicture();
public tblEmpPicture Pic
{
get { return _Pic; }
set
{
_Pic = value;
OnPropertChanged();
}
}
public async Task PutUserPicCommand()
{
try
{
IsBusy = true;
// Call your web service here
var employeesTaskServices = new TaskServices();
await employeesTaskServices.PutUserPicAsync(_Pic);
}
catch (Exception ex)
{
// Handle exception
}
finally
{
IsBusy = false;
}
}
請我將圖像轉換為二進制數據並將其保存到sql server。 我能夠將其他數據保存到sql server,但是不知道如何將圖像轉換為二進制文件並保存到數據庫中以及如何檢索和顯示圖像。
最佳做法是,除非確實需要,否則不應將映像直接保存到SQL Server中。 在此鏈接中了解更多。
要回答您的問題,請按照以下步驟操作。
將圖像轉換為Base64。
public static async Task<string> Convertbase64Async (Stream stream) { var bytes = new byte[stream.Length]; await stream.ReadAsync(bytes, 0, (int)stream.Length); string base64 = Convert.ToBase64String(bytes); return base64; }
現在,圖像將為字符串格式。 進行插入。
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
當要顯示圖像時,請使用SELECT查詢從SQL中檢索圖像。
將Base64轉換回Image格式。
public Image LoadImage(String base_64) { byte[] bytes = Convert.FromBase64String(base_64); Image image; using (MemoryStream ms = new MemoryStream(bytes)) { image = Image.FromStream(ms); } return image; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.