2012-03-16 122 views
0

如果我有像下面這樣的情況,我會在哪裏成功。處理圖像上傳並存儲在數據庫中。考慮到這個代碼,你將如何實現多個圖像上傳。 謝謝。在mvc3中上傳多張圖片

所以首先。

PropertyViewModel.cs 

... 
public byte[] ImageData { get; set; } 
public string ImageMimeType { get; set; } 

public PropertyViewModel(Property x) 
{ 
    .... 
    ImageData = x.ImageData; 
    ImageMimeType = x.ImageMimeType; 
} 

public void ToDomainModel(Property x) 
{ 
    .... 
    x.ImageData = ImageData; 
    x.ImageMimeType = ImageMimeType; 
} 

現已形成Create.cshtml剃刀頁

@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    ... 
    <input type="file" name="Image"/> 
} 

}

控制器來處理請求

[HttpPost] 
public ActionResult Create(PropertyViewModel newProperty, HttpPostedFileBase image) 
     { 
      if (ModelState.IsValid) 
      { 
       if (image != null) 
       { 
        newProperty.ImageMimeType = image.ContentType; 
        newProperty.ImageData = new byte[image.ContentLength]; 

        image.InputStream.Read(newProperty.ImageData, 0, image.ContentLength); 
       } 
       using (session...) 
       { 
        using (...begin transaction) 
        { 
         MyDomain.Property model = new MyDomain.Property(); 
         newProperty.ToDomainModel(model); 
         ..session save model 
         .. commiting session 
        } 
       } 
       return RedirectToAction("Index"); 
      } 
      else 
      { 
       return View(newProperty); 
      } 
     } 

回答

0
@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    ... 
    <input type="file" name="Image"/> 
    <input type="file" name="Image"/> 
    <input type="file" name="Image"/> 
    <input type="file" name="Image"/> 
} 

,或者如果瀏覽器支持HTML5,你可以選擇多上傳中的文件對話:

@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    ... 
    <input type="file" name="Image" multiple="multiple"/> 
} 

然後:

public ActionResult Create(PropertyViewModel newProperty, IEnumerable<HttpPostedFileBase> image) 
+0

謝謝你那太棒了。你如何實現編輯這個視圖模型的行動。在編輯操作中加載所有基於某個ID的圖像。謝謝 – BobRock 2012-03-16 13:15:34

+0

我會添加一個'IEnumerable Image {get;組; }屬性直接進入視圖模型並擺脫第二個動作參數。 – 2012-03-16 13:38:06

+0

然後我需要更改域屬性嗎?現在它的 --------- 公共虛擬字節[] ImageData { get {return _ImageData; } 集合 { if(_ImageData == value) return; _ImageData = value; } } 公共虛擬字符串ImageMimeType { {{_ImageMimeType; } set if(_ImageMimeType == value) return; _ImageMimeType = value; } } – BobRock 2012-03-16 13:50:47