【问题标题】:File Upload ASP.NET MVC Not Working文件上传 ASP.NET MVC 不工作
【发布时间】:2018-06-09 16:16:21
【问题描述】:

我已经尽力了,但是HttpPostedFileBase filee 始终是null

控制器动作

 public ActionResult UploadFile(HttpPostedFileBase filee)
        {
            try
            {
                if (filee.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(filee.FileName);
                    string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
                    filee.SaveAs(_path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }

剃刀视图

@{
    ViewBag.Title = "UploadFile";
}

<h2>UploadFile</h2>

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

    <div>
        @Html.TextBox("file", "", new { type = "file" }) <br />
        <input type="submit" value="Upload" />

        @ViewBag.Message

    </div>


}  

【问题讨论】:

  • 因为输入的文件名是file而不是filee。他们需要匹配。
  • 看看This Answer
  • 有什么好的理由吗?为了这。我们总是可以根据自己的意愿选择命名实例。雇员雇员=新雇员();
  • 如果您要否决我的问题,请提及改进。一个人知道什么是错的还不够吗?只需对问题投反对票即可。
  • @StephenMuecke 感谢您的帮助,非常感谢。

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


【解决方案1】:

要么将public ActionResult UploadFile(HttpPostedFileBase filee)中的参数名称更改为public ActionResult UploadFile(HttpPostedFileBase file),要么将输入名称@Html.TextBox("file", "", new { type = "file" })更改为@Html.TextBox("filee", "", new { type = "file" })

【讨论】:

    【解决方案2】:

    在处理松散类型视图时,您必须使用与 HttpPostedFileBase 对象名称相同的输入字段名称!

    例子:

        @{
            ViewBag.Title = "UploadFile";
        }
    
        <h2>UploadFile</h2>
    
        @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
    
            <div>
                @Html.TextBox("filee", "", new { type = "file" }) <br />
                <input type="submit" value="Upload" />
    
                @ViewBag.Message
    
            </div>
    
    }  
    

    或者如果您不想使用相同的名称? 你只需要使用紧密耦合的视图类型视图

    紧紧地
    示例:

    @model PROJECTNAME.Models.MODELNAME
    
            @{
                ViewBag.Title = "UploadFile";
            }
    
            <h2>UploadFile</h2>
    
            @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
    
                <div>
                    @Html.TextBox(model => model.YOURCOLUMNNAME , "", new { type = "file" }) <br />
                    <input type="submit" value="Upload" />
    
                    @ViewBag.Message
    
                </div>
    
        }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2011-07-08
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      相关资源
      最近更新 更多