我有一个MultipartForms,我可以在其中上传图像和其他表单值。虽然,表单值通过FormCollection属性正确接收,而上传文件始终显示HttpPostedFileBase属性中的空值。我通过论坛但我无法走到哪里错了。在这里,我做了什么请经历它并说出了什么是错的。谢谢朋友。
enter code here
CSHTML:
@using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="StaffImage" id="StaffImage" />
}
控制器
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection,HttpPostedFileBase File)
{
try
{
// TODO: Add insert logic here
StaffRegistration StaffReg = new StaffRegistration();
StaffReg.FirstName = collection["FirstName"].ToString();
StaffReg.LastName = collection["LastName"].ToString();
StaffReg.DateOfBirth = DateTime.Parse(collection["DateofBirth"]);
StaffReg.Nationality = collection["Nationality"].ToString();
StaffReg.Gender = collection["Gender"].ToString();
StaffReg.MaritalStatus = collection["MaritalStatus"].ToString();
StaffReg.BloodGroup = collection["BloodGroup"].ToString();
StaffReg.StaffName = collection["StaffName"].ToString();
StaffReg.MiddleName = collection["MiddleName"].ToString();
HttpPostedFileBase file = Request.Files["StaffImage"];
StaffRegistrationBusSer StaffRegBusSer = new StaffRegistrationBusSer();
StaffRegBusSer.AddStaffReg(StaffReg,file);
return RedirectToAction("Index");
}
数据层
public bool AddStaffRegistraiton(StaffRegistration staffRegistration,HttpPostedFileBase File)
{
staffRegistration.StaffImage = ConvertToByte(File);
using(SqlConnection Con = new SqlConnection(ConnectionString))
{
SqlParameter paramImage = new SqlParameter();
paramImage.ParameterName = "@StaffImage";
paramImage.Value = staffRegistration.StaffImage;
Cmd.Parameters.Add(paramImage);
Con.Open();
Cmd.ExecuteNonQuery();
}
return true;
}
ConvertToByte function:
public byte[] ConvertToByte(HttpPostedFileBase Image)
{
byte[] imagebyte = null;
BinaryReader Reader = new BinaryReader(Image.InputStream);
imagebyte = Reader.ReadBytes((int)Image.ContentLength);
return imagebyte;
}
答案 0 :(得分:0)
cshtml页面:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
@Html.LabelFor(model => model.StaffName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StaffName)
@Html.ValidationMessageFor(model => model.StaffName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="file" name="StaffImage" id="StaffImage" />
</div>
</div>
}
实际上我必须在View级别中包含multipart / form,而不是特定的上传文件。然后,我在.cshtml页面中修改了这样的内容。现在,我的代码工作正常