【问题标题】:Request.Files throws object reference not set - MVCRequest.Files 抛出未设置的对象引用 - MVC
【发布时间】:2018-07-10 18:16:07
【问题描述】:

我有一个奇怪的问题。

我想将上传的图片保存到我项目中的文件夹中。

这是来自控制器的代码:

 ......

 if (Request.Form["InputFile"] != null)
  {
     string directory = Server.MapPath("~/Content/UploadedFiles/");
     var file = Request.Form["InputFile"];
     string filename = fileService.GetFileName(directory, Request.Form["InputFile"]);
     Request.Files[0]?.SaveAs(filename);
 }

当调试器到达这一行时:

 Request.Files[0]?.SaveAs(filename);

应用程序针对Request.Files 抛出Object reference not set 错误。

在视图中我添加了

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

下面是代码:

<div class="form-group" style="margin-bottom: 0px;">
     <div class="col-md-8">
      @Html.TextBox("uploadFile", "", new { @class = "form-control", @required = "required" , @onChange= "readURL(this);" })
       </div>
<div class="col-md-3">
      <div class="fileUpload btn btn-success form-control">
       <span>Browse</span>
       @Html.TextBox("InputFile", "", new { type = "file", @class = "upload", @id = "uploadBtn" })
      </div>
    </div>
  </div> 

模型中的InputFile:

public HttpPostedFileBase InputFile { get; set; }

您能否建议尝试将所选图像保存到文件夹中?

【问题讨论】:

    标签: asp.net-mvc httppostedfilebase


    【解决方案1】:

    您正在使用 BeginForm() 的重载来添加路由值,而不是 html 属性。如果您检查正在生成的 html,您会发现 &lt;form&gt; 元素不包含 enctype = "multipart/form-data" 属性。

    将代码更改为(替换您的控制器和操作名称)

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

    此外,您的模型包含HttpPostedFileBase 的属性,因此不必使用Request.Form["InputFile"]Request.Files[0]。而是使用(假设您的 POST 方法中模型的参数名为 model

    if (model.InputFile != null && model.InputFile.ContentLength > 0) {
        .... // save file
    

    我还建议使用强类型 HtmlHelper 方法

    @Html.TextBoxFor(m => m.InputFile, new { type = "file", @class = "upload" })`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      相关资源
      最近更新 更多