我正在越來越薄的學習mvc3。我有下面的代碼在我的控制器用MVC上傳文件3
[HttpPost]
public ActionResult Accreditation(Accreditation accreditation)
{
if (ModelState.IsValid)
{
var fileUpload = Request.Files[0];
var uploadPath = Server.MapPath("~/App_Data/uploads");
using (var fs = new FileStream(Path.Combine(uploadPath, accreditation.PressCard.ToString()), FileMode.Create))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
context.Accreditations.Add(accreditation);
context.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PossibleNationalities = context.Nationalities;
ViewBag.PossibleNchis = context.Nchis;
ViewBag.PossibleMedia = context.Media;
ViewBag.PossibleEmploymentStatus = context.EmploymentStatus;
return View(accreditation);
}
}
這裏的景觀:
@using (Html.BeginForm("Accreditation", "Home", new { enctype = "multipart/form-data" }, FormMethod.Post))
{
@Html.ValidationSummary(true)
.............
.............
<div class="editor-field">
<input type="file" name="PressCard" id="PressCard" data-val-required="Press card is required" data-val="true"/>
@Html.ValidationMessageFor(model => model.PressCard)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Passport)
</div>
<div class="editor-field">
<input type="file" name="Passport" id="Passport" data-val-required="ID/Passport is required" data-val="true"/>
@Html.ValidationMessageFor(model => model.Passport)
</div>
....... ........
當我嘗試要上傳,我收到以下錯誤消息:
異常詳細信息:System.ArgumentOutOfRangeException:索引超出範圍。必須是非負數且小於集合的大小。 參數名稱:index
任何一個指向正確方向的指針?
對不起延遲。下面是新的代碼
[HttpPost]
public ActionResult Accreditation(Accreditation accreditation, HttpPostedFileBase Passport)
{
if (ModelState.IsValid)
{
var uploadPath = Server.MapPath("~/App_Data/uploads");
using (var fs = new FileStream(Path.Combine(uploadPath, accreditation.PressCard.ToString()), FileMode.Create))
{
var buffer = new byte[Passport.InputStream.Length];
Passport.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
context.Accreditations.Add(accreditation);
context.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PossibleNationalities = context.Nationalities;
ViewBag.PossibleNchis = context.Nchis;
ViewBag.PossibleMedia = context.Media;
ViewBag.PossibleEmploymentStatus = context.EmploymentStatus;
return View(accreditation);
}
}
感謝您的快速反饋,意味着很多 我改變了行動閱讀 [HttpPost] 公衆的ActionResult認證(認證認可,HttpPostedFileBase護照) { } 新的錯誤異常詳細信息: System.NullReferenceException:未將對象引用設置爲對象的實例。 –
你在哪裏有這樣的錯誤? – Samich