2016-08-04 32 views
-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; 
} 
+0

您的文件輸入具有'name =「StaffImage」'所以POST方法中的參數必須匹配 - public ActionResult Create(StaffReg模型,HttpPostedFileBase StaffImage)' - 不要更改第一個參數到你的模型(你永遠不需要使用FormCollection) –

+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> 
} 

其實我必須包括在視圖級別的multipart /表單,而不是特定的上傳files.Then,我在.cshtml頁面修改這個樣子。現在,我的代碼工作正常