2013-07-06 2 views
4

목록 사이트에서 작업 중입니다. 이미지를 업로드하고 데이터베이스의 경로를 저장하려고합니다.ASP.NET MVC 4 양식에서 파일을 가져올 수 없습니다.

문제는 단지 양식에서 업로드 된 파일을 검색 할 수없는 것 같습니다. 여기

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <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.Location) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Location) 
      @Html.ValidationMessageFor(model => model.Location) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Condition) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Condition) 
      @Html.ValidationMessageFor(model => model.Condition) 
     </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.PostedBy) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.PostedBy) 
      @Html.ValidationMessageFor(model => model.PostedBy) 
     </div> 

     <div class="editor-field"> 
      Upload Image <input type="file" name="listingImage" /> 
     </div> 

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

형태입니다 그리고 여기과 같이 설정을 나열하는 제품에 대한 나는 모델을 가지고 작업

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(Product product, HttpPostedFileBase listingImage) 
    { 
     if (listingImage == null) 
     { 
      return RedirectToAction("Index"); 
     } 
     if (ModelState.IsValid) 
     { 
      db.Products.Add(product); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(product); 
    } 

입니다.

public class Product 
{ 
    public int ID { get; set; } 

    public string Name { get; set; } 
    public string Description { get; set; } 
    public string Location { get; set; } 
    public string Condition { get; set; } 
    public decimal Price { get; set; } 
    public string PostedBy { get; set; } 

    public string PhotoPath { get; set; } 
} 

양식을 완성하고 제출할 때마다 listingImage가 null이고 색인으로 돌아갑니다.

내가 누락 된 자료가 있습니까?

감사합니다.

답변

2

양식 인코딩 유형을 "multipart/form-data"로 설정해야합니다. 그렇지 않으면 파일을 게시 할 수 없습니다.

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

그리고 그래, 당신 모델 데이터를 별도로 파일을 정의하고 이전과 같이 컨트롤러 액션을 선언 할 수 있습니다, 모델 클래스로 파일 필드를 포함 할 필요가 :

public ActionResult Create(Product product, HttpPostedFileBase listingImage) 
+0

고맙습니다.이 솔루션을 찾고있었습니다. – jaooe

1

listingImage은 모델의 일부가 아니며 나머지 Model.xx 속성과 동일한 바인딩을 갖지 않습니다.

당신은 HttpPostedFileBase listingImage을 포함하고 파일의 위치는이

@using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" })){ @* Forgot this line as Alex Skalozub told in his answer *@ 
@* code omitted *@ 

    <div class="editor-field"> 
     @Html.TextBoxFor(model => model.listingImage, new {type = "file"}) 
    </div> 
} 

같은 새로운 속성을 추가 할 수 있습니다 HTML에서

public ActionResult Create(Product product) 

에 컨트롤러 액션을 변경 Product를 업데이트 할 수 있고 당신이 할 수 절약

var path = Path.Combine(Server.MapPath("~/images/products"),product.listingImage.FileName); 
product.listingImage.SaveAs(path); 
+0

나는 시도하지 내 모델에서 HttpPostedFileBase를 포함하여 "Key null"이 될 수없는 줄이 있습니다. – jaooe