2009-09-08 40 views
1

我的數據庫中有一個類型爲image的字段,在我的模型(ADO.NET實體框架)中映射爲二進制文件。文件輸入框上傳圖像到數據庫

但不知怎的,我從輸入文件框中得到的圖像沒有被傳遞給對象。我知道這是因爲我打斷了我的動作和對象語言(我試圖上傳到數據庫的圖像是一個標誌)將屬性Flag設置爲null,這非常糟糕!它應該包含上傳的圖像。我還需要做點別的嗎?

下面是我的形式HTML代碼和我的動作代碼:

<% using (Html.BeginForm("Create", "Language", FormMethod.Post, 
      new {enctype="multipart/form-data"})) {%> 
    <fieldset> 
     <legend>Fields</legend> 
     <p> 
      <label for="Id">Id:</label> 
      <%= Html.TextBox("Id") %> 
      <%= Html.ValidationMessage("Id", "*") %> 
     </p> 
     <p> 
      <label for="Name">Name:</label> 
      <%= Html.TextBox("Name") %> 
      <%= Html.ValidationMessage("Name", "*") %> 
     </p> 
     <p> 
      <label for="Flag">Flag:</label> 
      <!-- 
      File box is a helper that I got from this link: 
      http://pupeno.com/blog/file-input-type-for-forms-in-for-asp-net-mvc/ 
      --> 
      <%= Html.FileBox("Flag") %> 
      <%= Html.ValidationMessage("Flag", "*") %> 
     </p> 
     <p> 
      <label for="IsDefault">IsDefault:</label> 
      <%= Html.TextBox("IsDefault") %> 
      <%= Html.ValidationMessage("IsDefault", "*") %> 
     </p> 
     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 

<% } %> 

我使用Visual Studio 2008

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Create(Language language) 
{ 
    // Here language.Flag is null. Shouldn't the Flag property be a 
    // binary field ready to be stored in the database along with the others? 
    if (!ModelState.IsValid || !_service.CreateLanguage(language)) 
    { 
     return View("Create", language); 
    } 
    return RedirectToAction("Index"); 
} 

我在做什麼錯?

回答

0

感謝您的回覆,幸好我找到了更好的方法。

我改變了操作方法簽名:
的[AcceptVerbs(HttpVerbs.Post) 公衆的ActionResult創建(語言語言)

到:
的[AcceptVerbs(HttpVerbs.Post) 公衆的ActionResult創建( HttpPostedFileBase標誌,語言語言)

然後,我將Flag文件名歸屬於language.Flag,並且只保留對文件所在的引用(這是因爲我們決定儘可能減小數據庫的大小,但我確信這是新的簽名也會起作用將文件轉換爲數據庫)。

希望這可以幫助其他人!

對不起,我不能給你一個讚許。沒有足夠的聲譽...

2

我已經能夠通過向我的操作方法添加HttpPostedFileBase參數來上傳文件。我不相信ASP.NET MVC會在這種情況下爲你自動填充語言參數的屬性。

+0

那麼,我該如何填充該屬性?謝謝! – 2009-09-08 13:18:46

+1

它爲我自動填充。我所要做的只是包含HttpPostedFileBase參數。在標記中,我沒有使用Html助手(儘管這應該沒問題)。我只是寫了 2009-09-08 13:37:35

1

文件上傳與普通帖子字段完全不同。您在Request.Files中有上傳。我在做這樣的事情把它撿起來

if (Request.Files.Count != 1 || Request.Files[0].ContentLength == 0) { 
    ModelState.AddModelError("Picture", "Picture is missing"); 
} else if (!IsImage(Request.Files[0].ContentType)) { 
    ModelState.AddModelError("Picture", "The picture must be a JPEG or PNG"); 
} else { 
    try { 
     Save(Request.Files[0].InputStream); 
    } catch { 
     ModelState.AddModelError("Picture", "Something is wrong with the picture, we couldn't open it"); 
    } 
} 

IsImage和保存實際上是在我的代碼比這複雜得多。如果你想將它保存到模型和數據庫中,你需要convert the stream into a byte array