【问题标题】:ASP .NET MVC uploaded file is always nullASP .NET MVC 上传的文件始终为空
【发布时间】:2021-12-23 17:36:55
【问题描述】:

我正在尝试上传 JSON 文件,但 MVC 控制器始终将其解释为 null。

查看:

<h3>OR</h3><br>
@Html.TextBox("jsonFile", null, new { type = "file" })

<div class="col-md-offset-2 col-md-10 ">
    <input type="submit" value="Create" class="btn btn-default submit-button" formaction="Create" />
</div>

控制器:

 public ActionResult Create(HttpPostedFileBase jsonFile)
 {
        MessageBox.Show("Create");
        String str;
        if (ModelState.IsValid)
        {
            if (jsonFile != null)
            {
                MessageBox.Show("File Upload Success");
                StreamReader jsonReader = new StreamReader(jsonFile.InputStream);
                str = jsonReader.ReadLine();

                MessageBox.Show(str);
            }
            else
            {
                MessageBox.Show("Null");   
            } 
            return RedirectToAction("Index");
        }
        return View(projectDetail);
    }

它是更大程序的一部分,我使用以下代码作为表单:

    @using (Html.BeginForm( new { htmlAttributes = new { enctype = "multipart/form-data" } } ))
    {
    }

我得到这个按钮来上传文件,文件上传也很好,因为我可以在点击提交之前看到它的上传状态。不知道为什么它在控制器中总是为空。

【问题讨论】:

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


    【解决方案1】:

    您是否使用“HTTPPOST”属性修饰了您的操作方法?我在您的创建操作中看不到这一点。

     public ActionResult Create(HttpPostedFileBase jsonFile)
    

    而且您还必须将表单更新为具有控制器和操作方法。

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

    【讨论】:

    • 嗨,创建动作已经有那个装饰器了。关于表单,正如我所说,它是更大程序的一部分,之前捕获的其他输入很好,只有文件抛出问题。我尝试了您建议的表单代码修改,我发现它现在也可以使用文件。非常感谢您的回答。
    • 很高兴听到它对您有所帮助。 :)
    猜你喜欢
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2013-04-12
    • 2015-05-29
    • 2020-01-20
    • 1970-01-01
    相关资源
    最近更新 更多