2013-10-04 36 views
16

所以我有一個項目,這是一個購物車,我要救的,而不是把它們上傳到服務器圖像數據庫中的圖像保存到數據庫,這裏是我的模型如何使用MVC 4

namespace ShoppingCart.Models 
{ 
    [Bind(Exclude = "ItemID")] 
    public class Item 
    { 
     [ScaffoldColumn(false)] 
     public int ItemID { get; set; } 
     [DisplayName("Category")] 
     public int CategoryID { get; set; } 
     [DisplayName("Brand")] 
     public int BrandID { get; set; } 
     [Required(ErrorMessage = "A Name is required")] 
     [StringLength(160)] 
     public string Title { get; set; } 
     public string Description { get; set; } 
     [Required(ErrorMessage = "Price is required")] 
     [Range(0.01, 100.00, 
      ErrorMessage = "Price must be between 0.01 and 500.00")] 
     public decimal Price { get; set; } 
     [DisplayName("Album Art URL")] 
     [StringLength(1024)] 

     public string ItemArtUrl { get; set; } 
     public byte[] Picture { get; set; } 

     public virtual Category Category { get; set; } 
     public virtual Brand Brand { get; set; } 
     public virtual List<OrderDetail> OrderDetails { get; set; } 
    } 
} 

所以我不確定如何去控制器插入圖像或視圖來顯示它們,我有搜索信息,但我真的找不到任何東西,我先使用實體​​框架代碼。

回答

36

有兩種簡單的方法可以做到圖像 - 一個是簡單地恢復圖像本身的控制器:

[HttpGet] 
    [AllowAnonymous] 
    public ActionResult ViewImage(int id) 
    { 
     var item = _shoppingCartRepository.GetItem(id); 
     byte[] buffer = item.Picture; 
     return File(buffer, "image/jpg", string.Format("{0}.jpg", id)); 
    } 

和視圖將只引用它:

<img src="Home/ViewImage/10" /> 

此外,您可以將其包含在ViewModel中:

viewModel.ImageToShow = Convert.ToBase64String(item.Picture); 

並在視圖中:

@Html.Raw("<img src=\"data:image/jpeg;base64," + viewModel.ImageToShow + "\" />"); 

對於數據存儲區,您只需使用字節數組(varbinary(max))或blob或任何兼容類型。

上傳圖片

在這裏,對象稱爲HeaderImage是一個的EntityFramework EntityObject。控制器看起來是這樣的:

[HttpPost] 
    public ActionResult UploadImages(HttpPostedFileBase[] uploadImages) 
    { 
     if (uploadImages.Count() <= 1) 
     { 
      return RedirectToAction("BrowseImages"); 
     } 

     foreach (var image in uploadImages) 
     { 
      if (image.ContentLength > 0) 
      { 
       byte[] imageData = null; 
       using (var binaryReader = new BinaryReader(image.InputStream)) 
       { 
        imageData = binaryReader.ReadBytes(image.ContentLength); 
       } 
       var headerImage = new HeaderImage 
       { 
        ImageData = imageData, 
        ImageName = image.FileName, 
        IsActive = true 
       }; 
       imageRepository.AddHeaderImage(headerImage); 
      } 
     } 
     return RedirectToAction("BrowseImages"); 
    } 

視圖可能看起來像:

  @using (Html.BeginForm("UploadImages", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
      { 
       <div class="row"> 
        <span class="span4"> 
         <input type="file" name="uploadImages" multiple="multiple" class="input-files"/> 
        </span> 
        <span class="span2"> 
         <input type="submit" name="button" value="Upload" class="btn btn-upload" /> 
        </span> 
       </div> 
      }