mvc3上传文件问题

@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset> <legend>Question</legend> <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div> <div class="editor-field">
         @Html.TextBoxFor(model => model.Title, new { style = "width: 400px" })
            @Html.ValidationMessageFor(model => model.Title)
        </div> <div class="editor-label">
            添加问题图片:
        </div> <div class="editor-field"> 
            选择上传文件:<input name="file" type="file" id="file" /> </div> <p> <input type="submit" value="Create" /> </p> </fieldset>
}

controller:

// POST: /Question/Create Question question,

[HttpPost] public ActionResult Create(Question question, HttpPostedFileBase file) { try { if (ModelState.IsValid) { if (file !=null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Resources"), fileName); file.SaveAs(path); QuestionResource resource = new QuestionResource(); resource.Url = path; question.Resources.Add(resource); } unitOfWork.QuestionRepository.Insert(question); unitOfWork.Save(); return RedirectToAction("Index"); } } catch(Exception ex) { //Log the error (add a variable name after DataException) ModelState.AddModelError("", question.Title + " " + question.Description + " " + file.ContentLength + " " + ex.Message + " Unable to save changes."); } return View(question); }

在控制器中:HttpPostedFileBase file获取不到上传的文件。调试显示null。

 

如何获取到上传的文件?谢谢

呼啦一阵风
浏览 367回答 11
11回答

守着一只汪

你 這樣 讀取this.HttpContext.Request.Files。不要加到參數里。

蝴蝶不菲

打不开。一闪就消失了

慕森王

@二手 程序员: 那图片上传成功了吗

慕容森

@二手 程序员: 都打不开??博客园其他页面能打开吗?

aluckdog

@二手 程序员: 我这边打开很快啊,你再试试吧
打开App,查看更多内容
随时随地看视频慕课网APP