我正在尝试将.csv文件上传到SQL数据库中,但控制器操作似乎根本没有抓取文件。查看代码,我一定错过了一篇文章:
查看:
@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>
}
控制器:
[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,不知道可能会发生什么,因为它在视图中被命名并且我有post方法围绕它。它会一直下降到var filePath = uploadFile(csvFile.InputStream);
然后中断,因为该方法试图传递空值。谢谢!
答案 0 :(得分:2)
当我尝试使用MVC将文件上传到db时,我遇到了这个问题,我正在使用scaffolded视图(所以它也传回了一个带有表单的对象),所以它可能有点不同。
在HTML.BeginForm()调用中,您需要添加属性enctype =“multipart / form-data”
@using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post, new {enctype="multipart/form-data"}))
答案 1 :(得分:1)
我认为您需要将enctype='multipart/form-data'
添加到<form>
using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
答案 2 :(得分:1)
您需要更改表单声明。尝试添加enctype =&#34; multipart / form-data&#34;到你的表格声明。
@using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
答案 3 :(得分:0)
您需要将以下内容添加到表单声明中:
@using (Html.BeginForm("UploadValidationTable", "Home", null,FormMethod.Post, new { enctype = "multipart/form-data" }))