-1
我有一個MultipartForms,其中我可以上傳圖像和其他表單值。雖然表單值通過FormCollection屬性正確接收,而上傳文件總是在HttpPostedFileBase Property中顯示空值。我通過論壇,但我無法得到哪裏去錯了。在這裏,我做了什麼請通過它並說出了什麼錯,感謝朋友。Asp.NET MVC - Fileupload圖像值在httppost方法中顯示空值
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;
}
您的文件輸入具有'name =「StaffImage」'所以POST方法中的參數必須匹配 - public ActionResult Create(StaffReg模型,HttpPostedFileBase StaffImage)' - 不要更改第一個參數到你的模型(你永遠不需要使用FormCollection) –
你可以在上傳文件時從瀏覽器控制檯添加請求和響應嗎? –