上传的文件为空

时间:2013-02-20 02:05:11

标签: c# html asp.net-mvc file-upload asp.net-mvc-4

在ASP.NET MVC4中,文件上载视图始终向控制器发送null。 我不知道为什么,我不知道如何修复它,搜索已被证明是无用的......

控制器方法:

[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase file)
{}

查看:

@using (Html.BeginForm("uploadCustomImage", "W", new { id=ViewBag.id }, FormMethod.Post, new { enctype = "multipart/form-data", name="uploadingimage" }))
{ 
    <input name="file" id="file" type="file" />
    @Html.SubmitButton()
}

它进入控制器很好,所以路由都很好。但文件始终为null。我尝试了几种不同的东西:重命名输入/对象,不使用文件参数并调用它: HttpPostedFileBase文件= Request.Files [“file”]; (结果也是空的)

我尝试将formcollection包含为参数(包含和不包含不必要的表单元素)。这个文件仍然是空的。

我当然在选择提交之前选择一个文件= P我尝试了多个文件;有非常基本的文件名(没有奇怪的unicode,甚至没有空格),也有更奇怪的文件名。大文件,小文件。

一切都出来了!我哪里出错?

2 个答案:

答案 0 :(得分:0)

你的名字没有对齐...你需要在你的控制器中建模绑定你名为“postingFile”的文件控件

答案 1 :(得分:0)

试试这样:

@using (Html.BeginForm("uploadCustomImage", "W", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   <input name="fileToUpload" type="file" />
   <input type="submit" />
}

[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase fileToUpload)
{}

<强> [编辑]

我刚刚在我正在开发的项目中实现了一个上传功能,但它确实有效。

@using (Html.BeginForm("Import", "MY_CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file"  id="UploadedXlsFile" name="UploadedXlsFile"/>

    <input type="submit" id="Submit" name="Submit" value="Submit"/>

}


public ActionResult Import()
{
    if (Request.Files["UploadedXlsFile"].ContentLength > 0)
    {
       .............Do stuff ................
    }
}

之前的代码适合我。如果我在Action方法中放置一个断点,我可以看到该文件不是null。