【问题标题】:CSV file upload errorCSV 文件上传错误
【发布时间】:2013-09-18 16:59:27
【问题描述】:

当我想尝试在ASP.Net MVC 中上传文件时,我收到以下错误。

文件错误

administratorPortal.dll 中出现“System.NullReferenceException”类型的第一次机会异常

文件错误

线程 '' (0x21e4) 已退出,代码为 0 (0x0)。 在 administratorPortal.dll 中发生了“System.NullReferenceException”类型的第一次机会异常

在我看来

<form action="../../Controllers/patientAppointmentController.cs" method=post>
<input id="model" type="file" name="fileUpload" data-val="true" data-val-required="File is required" />
<input class="btn btn-primary" type="submit" value="Import" />
</form>  

在我的控制器中

public ActionResult CSVUpload(HttpPostedFileBase fileUpload)
    {
        try
        {
            Debug.Write(fileUpload.ContentLength);

            if (fileUpload.ContentLength < 0 || fileUpload == null)
            {
                Debug.Write("unable to detectFile");
            }
        }
        catch
        {
            Debug.Write("file error");
        }
        return View();
    }

有一些问题,我什至无法将文件传递给控制器​​。我尝试了许多在互联网上找到的不同方法,但它们都不适合我。

  • 我已经安装了 CSVhelper

【问题讨论】:

  • 您在表单上缺少enctype="multipart/form-data"

标签: c# asp.net-mvc


【解决方案1】:

表单似乎指向了错误的位置

<form action="/patientAppointment/CSVUpload" method="post" enctype="multipart/form-data">
  <input id="model" type="file" name="fileUpload" data-val="true" data-val-required="File is required" />
  <input class="btn btn-primary" type="submit" value="Import" />
</form>  

正如@Fals 所指出的,您还需要使用HttpPost 属性来装饰该方法,以表明它接收到一个表单。

[HttpPost]
public ActionResult CSVUpload(HttpPostedFileBase fileUpload)
{
    try
    {
        Debug.Write(fileUpload.ContentLength);

        if (fileUpload.ContentLength < 0 || fileUpload == null)
        {
            Debug.Write("unable to detectFile");
        }
    }
    catch
    {
        Debug.Write("file error");
    }
    return View();
}

【讨论】:

  • 别忘了动作的HttpPost属性,上面我看不到!
  • 我仍然有上述错误。尽管我遵循了 enctype 和 [HttpPost],但在 administratorPortal.dll 中发生了“System.NullReferenceException”类型的第一次机会异常。还有什么我可能错过的吗?
【解决方案2】:

您的表单操作不应该指向资源的地址而不是 .cs 文件吗?

【讨论】:

  • 你好欧文,你说的资源地址是什么意思?
  • 哦,正如@Kami 指出的那样,您的表单操作似乎不正确,请注意他/她将其更改为:'action="/patientAppointment/CSVUpload" '?
猜你喜欢
  • 2015-10-20
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
  • 2015-08-20
  • 1970-01-01
相关资源
最近更新 更多