2012-09-24 59 views
3

我在我的视图中有@Html.BeginForm这是假设允许用户上传图像并添加一些关于图像的细节。ASP.NET MVC HttpPostedFIleBase为空

这里查看:

@Html.BeginForm("SaveImage", "Listing", FormMethod.Post, new { enctype = "multipart/form-data" }))) { 
<div id="modalAddImage" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
    <div class="modal-header"> 
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> 
        <h3 id="myModalLabel">Modal header</h3> 
    </div> 
    <div class="modal-body"> 
    <p>Image</p> 
    <input type="file" name="file"></input> 

    @foreach (Image translation in Model.Listing.Images) 
    { 
     @Html.TextBoxFor(m => m.Description) 
    } 
    </div> 
    <div class="modal-footer"> 
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> 
    <button class="btn btn-primary">Save changes</button> 
</div> 
</div> 
} 

我这个是别的东西前右有不同的@Html.BeginForm

这是我的控制器:

[HttpPost] 
    public ActionResult SaveImage(HttpPostedFileBase file) 
    { 
     if (file!= null && file.ContentLength > 0) 
     { 
      var fileName = Path.GetFileName(file.FileName); 
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
      file.SaveAs(path); 
     } 

     return View("Maintain"); 
    } 

当我把一个破发点中SaveImage,文件始终为空。我试图上传大小图片。

任何人都可以看到我要去哪里可怕的错?

+0

“文件”对于您在此处给出的扩展使用也没有定义。为什么不尝试在输入类型文件和控制器参数上使用“uploadedFile”之类的东西? – Bardo

+0

检查我的答案在http://stackoverflow.com/questions/16102235/upload-image-mvc-always-null –

回答

3

您可以简单地这样做:

[HttpPost] 
public ActionResult SaveImage(HttpPostedFileBase file) 
{ 
    if (Request.Files.Count > 0) 
    { 
     foreach (string upload in Request.Files) 
     { 
      if (upload != null) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);  
       Request.Files[upload].SaveAs(path); 

      } 
     } 
    } 
    return View("Maintain"); 
} 
+3

这可能是一个坏主意,直接在操作中使用请求和HttpPostedFileBase只是为了避免这种情况,仍然为什么? – VJAI

1

为具有那么同样的问题,意识到我没有在我的形式规定(ENCTYPE = “的multipart/form-data的”)

相关问题