【问题标题】:Xamarin form - how to upload and retrieve image using sql server web apiXamarin 表单 - 如何使用 sql server web api 上传和检索图像
【发布时间】:2018-06-25 07:43:59
【问题描述】:

我需要将图像作为二进制数据上传并在此处检索是我的代码 网页接口

   [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();

MainVewModel

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,但不知道如何将图像转换为二进制并保存到数据库以及如何检索和显示图像。

【问题讨论】:

    标签: c# sql-server xamarin xamarin.forms


    【解决方案1】:

    作为最佳实践,除非确实有必要,否则不应将图像直接保存到 SQL Server 中。 Read more in this link.

    要回答您的问题,请按照以下步骤操作。

    1. 将图像转换为 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;
      }
      
    2. 现在图像将采用字符串格式。进行插入。

      INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);

    3. 当您想要显示图像时,请使用 SELECT 查询从 SQL 中检索图像。

    4. 将 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;
      }
      

    供参考:Bas64 to imageBest practices

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2019-03-13
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 2014-08-13
      • 2016-12-06
      相关资源
      最近更新 更多