我正在越来越薄的学习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