我正在尝试将 .csv 文件上传到 SQL 数据库,但 Controller 操作似乎根本没有抓取该文件。查看代码,我一定遗漏了一段:
查看:
@using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post))
{
<table style="margin-top: 150px;">
<tr>
<td>
<label for="csvFile">Filename:</label>
</td>
<td>
<input type="file" name="csvFile" id="csvFile"/>
</td>
<td><input type="submit" value="Upload"/></td>
</tr>
</table>
}
Controller :
[HttpPost]
public JsonResult UploadValidationTable(HttpPostedFileBase csvFile)
{
var inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
var cc = new CsvContext();
var filePath = uploadFile(csvFile.InputStream);
var model = cc.Read<OutstandingCreditCsv>(filePath, inputFileDescription);
try
{
var entity = new OutstandingCreditCsv();
foreach (var item in model)
{
entity.PoNumber = item.PoNumber;
entity.CreditInvoiceDate = item.CreditInvoiceDate;
entity.CreditInvoiceNumber = item.CreditInvoiceNumber;
entity.CreditInvoiceAmount = item.CreditInvoiceAmount;
}
}
catch(LINQtoCSVException ex)
{
}
return Json(model, "text/json");
}
csvFile 只是显示为 null,不知道会发生什么,因为它在 View 中被命名并且我有围绕它的 post 方法。它一直下降到 var filePath = uploadFile(csvFile.InputStream);
然后中断,因为该方法试图传递空值。谢谢!
最佳答案
我在尝试使用 MVC 将文件上传到数据库时遇到了这个问题,我使用的是脚手架 View (所以它也传回了一个带有表单的对象),所以它可能有点不同。
在您的 HTML.BeginForm() 调用中,您需要添加属性 enctype="multipart/form-data"
@using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post, new {enctype="multipart/form-data"}))
关于c# - 尝试上传时 Controller 操作未从 View 中抓取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596701/