在ASP.NET MVC中上传图像

我有一个上传表单,我想通过我的信息,如图像和其他领域,但我不知道我怎么能上传图像..

这是我的控制器代码:

[HttpPost] public ActionResult Create(tblPortfolio tblportfolio) { if (ModelState.IsValid) { db.tblPortfolios.AddObject(tblportfolio); db.SaveChanges(); return RedirectToAction("Index"); } return View(tblportfolio); } 

这是我的观点代码:

 @model MyApp.Models.tblPortfolio <h2>Create</h2> @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) <fieldset> <legend>tblPortfolio</legend> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.ImageFile) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.ImageFile, new { type = "file" }) @Html.ValidationMessageFor(model => model.ImageFile) </div> <div class="editor-label"> @Html.LabelFor(model => model.Link) </div> <div class="editor-field"> @Html.EditorFor(model => model.Link) @Html.ValidationMessageFor(model => model.Link) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } 

现在我不知道如何上传图像并将其保存在服务器上..我如何设置图像名称由Guid.NewGuid(); ? 或者我怎样才能设置图像path?

首先,你需要改变你的观点,以包括以下内容:

 <input type="file" name="file" /> 

然后你需要改变你的发布ActionMethod采取一个HttpPostedFileBase ,如下所示:

 [HttpPost] public ActionResult Create(tblPortfolio tblportfolio, HttpPostedFileBase file) { //you can put your existing save code here if (file != null && file.ContentLength > 0) { //do whatever you want with the file } } 

你可以从Request使用Request.Files集合,如果单个file upload的情况下,只需要使用Request.Files[0]从第一个索引读取:

 [HttpPost] public ActionResult Create(tblPortfolio tblportfolio) { if(Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files[0]; if (file != null) { // business logic here } } } 

在多file upload的情况下,你必须迭代Request.Files集合:

 [HttpPost] public ActionResult Create(tblPortfolio tblportfolio) { for(int i=0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; if (file != null) { // Do something here } } } 

如果你想通过ajax上传没有页面刷新的文件,那么你可以使用这个使用jquery插件的文章