2012-11-14 47 views
0

我有一個MVC 4項目,我需要將數據寫入到數據庫中,包括在「創造」視圖的圖像。將數據寫入數據庫,包括圖像

我發現如何上傳圖像的幾個例子。但是沒有一個例子和html文件上傳控件一起有一些額外的輸入字段。

使我不知道是否有可能瀏覽到的圖像,並在其他領域,並按填寫「發送」按鈕,並接收在控制器中的所有數據,並將這些方法具體爲:

[HttpPost] 
public ActionResult Create(FormCollection formCollection) 
{ 
    foreach (var key in formCollection.AllKeys) 
    { 
    if (key == "file") 
    { 
     foreach (string s in Request.Files) 
     { 
      HttpPostedFileBase file = Request.Files[s]; 
      if (file.ContentLength > 0) 
      { 
      } 
     } 
     } 
    } 
} 

這是視圖:

@using (Html.BeginForm("Create", "Item", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Item</legend> 

     <div class="editor-label"> 
      Description: 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Description) 
      @Html.ValidationMessageFor(model => model.Description) 
     </div> 
     <div class="editor-label"> 
      Image: 
     </div> 

     <input type="file" name="file" id="file" /> 

     <p> 
      <input type="submit" value="send" /> 
     </p> 
    </fieldset> 
} 

Request.Files在這種情況下總是空的。

我錯過了什麼?

+1

從你的代碼一切都看起來不錯。你是否檢查過螢火蟲,仔細檢查Content Type'multipart/form-data'是否正在發送? – eth0

回答

2

你也應該能夠做到這一點使用強類型的編輯模式:

public class MyDataEditModel 
{ 
    public string Description { get; set; } 
    public HttpPostedFileBase File { get; set; } 
} 


[HttpPost] 
public ActionResult Create(MyDataEditModel model) 
{ 
    // is model.File null here? 
} 
1

您可以按照this tutorial它展示瞭如何在ASP.NET MVC中上傳圖片

這裏操作如下所示。

[HttpPost] 
public ActionResult Index(UserModel model, HttpPostedFileBase file) 
{} 

隨着文件發佈,一個UserModel也發佈,它從頁面獲取其他數據,這是你想要的。