我正在学习 mvc3。我的 Controller 中有以下代码
[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);
}
}
这是 View :
@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:索引超出范围。必须为非负数且小于集合的大小。 参数名称:索引
有人能指出正确的方向吗?
<小时/>抱歉耽搁了。这是新代码
[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);
}
}
最佳答案
真的在上传数据吗?我建议你用这种方式。创建一个与输入字段同名的 HttpPostedFileBase 类型参数,并测试其内容长度属性。
不要忘记对参数和输入标记使用相同的名称。
检查此链接将是您继续前进的最快方式。
关于c# - 使用 MVC 3 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7471179/