2014-05-05 151 views
0

我试图将图像上传到我的App_Data文件夹中。我使用了HttpPostedFileBase,但由于某种原因它总是返回null。 这里是我的创建方法:MVC获取图像的NULL路径

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult mkCreate(HttpPostedFileBase file) 
    { 
     if (file.ContentLength > 0) 
     { 
      var fileName = Path.GetFileName(file.FileName); 
      var path = Path.Combine(Server.MapPath("~/App_Data"), fileName); 
      file.SaveAs(path); 
     } 
     return View(); 

    } 

这是我的看法(Create.cshtml):

@using (Html.BeginForm("mkCreate", "Resim", FormMethod.Post, new { enctype= "multipart/form-data" })) 
{ 
    <table> 
     <tr> 
      <td>Image:</td> 
      <td><input type="file" name="Images" id="Images" multiple /></td> 
     </tr> 
     <tr> 
      <td>&nbsp;</td> 
      <td><input type="submit" name="submit" value="Upload" /></td> 
     </tr> 
    </table> 
} 

能否请你帮我上传图片到我的App_Data文件夹? 在此先感谢。

回答

1

你的图像模型可能是这样的:

public class Image 
{ 
    public IEnumerable<HttpPostedFileBase> Images { get; set; } 
} 

你的控制器应该有一个这样的动作:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(Image image) 
{ 
    foreach (var file in image.Images) 
     { 
      if (file.ContentLength > 0) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       var path = Path.Combine(Server.MapPath("~/App_Data"), fileName); 
       file.SaveAs(path); 
      } 
     } 
    ViewBag.Message = "Image(s) uploaded successfully"; 
    return View(); 
} 

最后你的看法可能是这样的:

@model AppName.Models.Image 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Image Upload Test</h2> 

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype "multipart/form-data" })) 
@Html.AntiForgeryToken() 
@Html.ValidationSummary(true) 
{ 
<table> 
    <tr> 
     <td>Image:</td> 
     <td><input type="file" name="Images" id="Images" multiple /></td> 
    </tr> 
    <tr> 
     <td>&nbsp;</td> 
     <td><input type="submit" name="submit" value="Upload" /></td> 
    </tr> 
</table> 
} 
+0

这是我尝试后得到的结果:“所需的防伪表单字段”__RequestVerificationToken“不存在” –

+1

哦,因为您在控制器上使用了validateantiforryry标记行动,你必须在你的表单上使用@ Html.AntiForgeryToken()。请再次检查编辑的代码。 – InsParbo

+0

谢谢你!有效! –

0

与本试加ENCTYPE

public ActionResult Create(HttpPostedFileBase file) 
{ 
//Rest of the code 
} 

查看

@using (Html.BeginForm("YourMethod", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" })) 
     { 
      <input type="file" name="file" id="Images" multiple /> 
     } 
+0

我试过,但返回null太.. –

+0

只包含''中Html.BeginForm()' – Nilesh

+0

仍然得到空enctype' :( –