【问题标题】:File upload always null, error object reference not set to an instance of an object文件上传始终为空,错误对象引用未设置为对象的实例
【发布时间】:2017-11-01 01:46:58
【问题描述】:

我正在尝试上传单个 .txt 文件,并阅读其内容。我正在使用IFormFile 来做到这一点。我的控制器基本上就像

public IHttpActionResult PostCellInfo(IFormFile file)
{

    using (var reader = new StreamReader(file.OpenReadStream()))
    {

        var fileContent = reader.ReadToEnd();
    }
}

我在索引中的表格是

  <form name="upload" method="post" enctype="multipart/form-data" action="api/CellInfoes">
        <div>
            <input name="file" type="file" />
            <input type="submit" value="upload" />
        </div>
    </form>

但错误仍然显示

"ExceptionMessage":"对象引用未设置为 对象。”

我认为“文件”总是null。任何想法为什么?

我已经读到名称必须匹配 - 但我认为这在我的代码中是可以的。

【问题讨论】:

  • 确保您在表单操作属性中使用了正确的操作方法。并将您的操作方法参数更改为HttpPostedFileBase 类型。并将 [HttpPost] 属性添加到您的帖子操作中

标签: c# asp.net asp.net-web-api model-view-controller asp.net-web-api2


【解决方案1】:

参数应该是IList&lt;IFormFile&gt; files

public IHttpActionResult PostCellInfo(IList<IFormFile> files)
{
     foreach (var file in files) {
        if (file.Length > 0) {
            using (var reader = new StreamReader(file.OpenReadStream()))
            {  
               var fileContent = reader.ReadToEnd();
            }
        }
     }
}

同时更改视图中的名称属性:

<form name="upload" method="post" enctype="multipart/form-data" action="api/CellInfoes">
        <div>
            <input name="files" type="file" />
            <input type="submit" value="upload" />
        </div>
    </form>

我尚未对此进行测试,但它应该会为您指明正确的方向。 如果你想在没有集合的情况下使用IFormFile,你应该检查这个post

【讨论】:

  • 您好,感谢您的快速回复。不幸的是,没有任何改变,在发送 POST 请求后调试时,它仍然显示“files = null”。
猜你喜欢
  • 2011-07-09
  • 2012-08-31
  • 2011-11-21
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多