【问题标题】:ASP.NET MVC3 RAZOR: File Upload gives zero as file countASP.NET MVC3 RAZOR:文件上传为零作为文件计数
【发布时间】:2012-03-13 18:29:39
【问题描述】:

我需要使用带有 RAZOR 的 MVC3 将多个文件上传到 Web 服务器。我有以下代码。在控制器中,文件计数为零。如何更正它以获取正在上传的实际文件数量并获取内容?

public class MyFileController : Controller
{

    public ActionResult MyFileProcessActionTest()
    {
        return View();
    }

    [HttpPost]
    public ActionResult MyFileProcessActionTest(IEnumerable<System.Web.HttpPostedFileBase> files)
    {

        int fileCount = files.Count<System.Web.HttpPostedFileBase>();
        return RedirectToAction("Index");
    }
}

查看

@{
ViewBag.Title = "MyFileProcessActionTest";
}

<h2>MyFileProcessActionTest</h2>

@using (Html.BeginForm())
{

<input type="file" name="files" id="file1" />
<input type="file" name="files" id="file2" />

<input type="submit"  />

}

阅读:

  1. Binding HttpPostedFileBase using Ajax.BeginForm

  2. ASP.NET MVC 上传和下载文件 http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files

  3. How do I Validate the File Type of a File Upload?

  4. MVC 3 file upload and model binding

【问题讨论】:

    标签: asp.net .net asp.net-mvc razor


    【解决方案1】:

    更改您的表单以匹配以下内容

    @using(Html.BeginForm("action","controller",FormMethod.Post,new{encType = "multipart/form-data"})){
    {
    
    <input type="file" name="files[0]" id="file1" />
    <input type="file" name="files[1]" id="file2" />
    <input type="file" name="files[2]" id="file3" />
    
    <input type="submit"  />
    
    }
    

    索引 0,1,2 将允许 modelbinder 绑定到 IEnumerable 此外,encType 在发布文件到服务器时也必须指定

    【讨论】:

    • 谢谢。工作。 @using (Html.BeginForm("MyFileProcessActionTest", "MyFile", FormMethod.Post, new { enctype = "multipart/form-data" })) {
    • 我得到file,因为nullRequest.Files.Count 也是0,如果formAjaxForm 并且还有routeValues 会有什么区别吗?
    • bjan,我没有用 ajax 测试过,但我相信它应该可以使用 ajax。
    • @bjan 你不能用 ajax 上传文件...你应该在谷歌上搜索 How to upload a file with ajax using an iframe
    【解决方案2】:

    您必须在form 标记中包含enctype 属性以指示表单应包含文件。

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

    【讨论】:

    • 对于包含文件上传的表单,人们经常会错过 enctype="multipart/form-data"
    • 我相信我们也不能使用GET 方法发布文件
    • 我得到file,因为nullRequest.Files.Count 也是0,如果formAjaxForm 并且还有routeValues 会有什么区别吗?
    • @bjan 你不能用 ajax 上传文件...你应该在谷歌上搜索 How to upload a file with ajax using an iframe
    猜你喜欢
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2012-12-22
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多