2014-02-24 109 views
10

我有這個控制器和我所試圖做的是將圖像發送到控制器的(字節),這是我的控制器:MVC HttpPostedFileBase總是空

[HttpPost] 
public ActionResult AddEquipment(Product product, HttpPostedFileBase image) 
{ 

      if (image != null) 
      { 
       product.ImageMimeType = image.ContentType; 
       product.ImageData = new byte[image.ContentLength]; 
       image.InputStream.Read(product.ImageData, 0, image.ContentLength); 
      } 

      _db.Products.Add(product); 
      _db.SaveChanges(); 

      return View(); 
} 

和我的看法:

@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post)) { 

    <fieldset> 
     <legend>Product</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Name) 
      @Html.ValidationMessageFor(model => model.Name) 
     </div> 

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

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Price) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Price) 
      @Html.ValidationMessageFor(model => model.Price) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Category) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Category) 
      @Html.ValidationMessageFor(model => model.Category) 
     </div> 

     <div> 
     <div>IMAGE</div> 
     <input type="file" name="image" /> 

     </div> 


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

但問題是,我的控制器上的圖像值常是空的,我不能似乎得到的HttpPostedFileBase任何信息

回答

23

您需要與萬畝添加encType ltipart /形式數據。

@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post, new {enctype = "multipart/form-data" })) { 

您可以隨時將其添加到您的模型太如下,只要它是一個ViewModel:

public class Product 
{ 
    public Product() 
    { 
     Files = new List<HttpPostedFileBase>(); 
    } 

    public List<HttpPostedFileBase> Files { get; set; } 
    // Rest of model details 
} 

您可以通過即

[HttpPost] 
public ActionResult AddEquipment(Product product) 
{ 
    var file = model.Files[0]; 
    ... 
} 
去除未所需參數檢索的文件
+0

真棒!感謝您的快速響應! –

+0

@RiquelmyMelara沒有probs,我也會改善答案。 – hutchonoid

+0

他的「產品」對象是我猜實體框架「實體」類型,因此添加另一個屬性可能會破壞他的代碼,除非他修復了配置 –

0

嘗試在Action方法的頂部執行此操作:

[HttpPost] 
    public ActionResult AddEquipment(Product product, HttpPostedFileBase image) 
    { 
     image = image ?? Request.Files["image"]; 
     // the rest of your code 
    } 

和形式應該有 「的multipart/form-data的」 的加密類型上傳文件:

@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post, new {enctype = "multipart/form-data" })) {