10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#で画像をDBに保存するAPI

Last updated at Posted at 2015-08-11

前提

HTMLのmultipart/form-dataで送られてきた画像について処理をする.NET APIを作る。
DB周りはEntityFrameworkを利用
DBの画像バイナリを保存する列の型はvarbinary(max)を想定

画像をDBにinsertする場合

下記のように定義したメソッドを利用すればOK

public void insertToDB()
{
  Entities DB = new Entities();
  MemoryStream memory;
  var postedFiles = HttpContext.Current.Request.Files;
  foreach (string file in postedFiles)
  {
    using (memory = new MemoryStream())
    {
      postedFiles[file].InputStream.CopyTo(memory);
      DB.tImages.Add(new tImages { bImage= memory.ToArray() });
    }
  }

  DB.SaveChanges();
}

画像をDBから取得する場合

ApiControllerで下記のGetメソッドを定義してやれば画像がURLベースで利用できる

public HttpResponseMessage Get(int id)
{
  Entities DB = new Entities();
  HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

  result.Content = new StreamContent(new MemoryStream(DB.tImages
        .Where(img => img.id== id)
        .Select(img=> img.bImage)
        .First()));
  return result;
}

わりかし簡単

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?