使用MVC将多个图像保存到数据库

时间:2016-10-15 11:04:03

标签: asp.net-mvc entity-framework

我的代码只保存第一个输入图像。我找到this link来了解如何处理多个图像。如果我将HttpPostedFileBase更改为HttpPostedFileBase[],则无法将InputStreamContentLength用于HttpPostedFileBase image

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Color,CategoryId,GenderId,Image")] Product product, HttpPostedFileBase image)
    {
        if (ModelState.IsValid)
        {
            byte[] imagee = null;
            if (Request.Files.Count > 0)
            {
                image = Request.Files[0];
                using (BinaryReader br = new BinaryReader(image.InputStream))
                {
                    imagee = br.ReadBytes(image.ContentLength);
                }
            }
            product.Image = imagee;
            db.Products.Add(product);
            db.SaveChanges();
            return RedirectToAction("Index");
    }

我只展示了这样一张图片:

<img class="img-rounded img-responsive" src="data:image/jpg;base64,@System.Convert.ToBase64String(item.Image)" width="250" height="400" />

如何存储多个图像并显示它们?

1 个答案:

答案 0 :(得分:1)

正如Stephen在评论中提到的,您当前的实体类定义用于存储针对产品的单个图​​像(一对一)。如果您希望图像具有多个图像,则应考虑为图像创建另一个表,并在它们之间建立一对多的连接。

public class Product
{
  public int Id { set; get;}
  public string Name { set; get;}
  public string Color { set; get;}
  // Add other properties needed as well

  public ICollection<Image> Images { set; get;}
}
public class Image
{
  public int Id { set; get;}
  public byte[] ImageData { set; get;}
  public int ProductId { set; get;}
}

现在在你的HttpPost动作中,

[HttpPost]
public ActionResult Create([Bind(Include = "Id,Name,Color,CategoryId,GenderId")]
                          Product product, IEnumerable<HttpPostedFileBase> images)
{
     if (ModelState.IsValid)
     {
         db.Products.Add(product);

         if (images!=null)
         {
            var imageList= new List<Image>();
            foreach(var image in images)
            {
               using (var br = new BinaryReader(image.InputStream))
               {
                 var data = br.ReadBytes(image.ContentLength);
                 var img=new Image { ProductId=product.Id };
                 img.ImageData = data;
                 imageList.Add(img);
               }
            }
            product.Images = imageList;
         }
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(product);
}