ASP .NET MVC 上传的文件始终为空

问题描述 投票:0回答:1

我正在尝试上传 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个回答
0
投票

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

 public ActionResult Create(HttpPostedFileBase jsonFile)

您还必须如下更新您的表单以具有控制器和操作方法。

@using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new { id = "FormCreate", enctype = "multipart/form-data"}))
© www.soinside.com 2019 - 2024. All rights reserved.