在MVC中上传/显示图像4

任何人都知道如何使用entity framework从数据库上传/显示图像的一步一步的教程? 我已经检查了代码片段,但是我仍然不清楚它是如何工作的。 我没有代码,因为除了写上传表格之外,我迷路了。 任何(我的意思是任何)的帮助,不胜感激。

在旁注中,为什么没有任何书籍涵盖这个话题? 我有Pro ASP.NET MVC 4和专业MVC4,他们没有提到它。

看看我的文章上传图片,或者你可以使用下面描述的相同的代码;
您的查看代码;

 @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <label for="file">Upload Image:</label> <input type="file" name="file" id="file" style="width: 100%;" /> <input type="submit" value="Upload" class="submit" /> } 

你的控制器应该有接受HttpPostedFileBase action方法;

  public ActionResult FileUpload(HttpPostedFileBase file) { if (file != null) { string pic = System.IO.Path.GetFileName(file.FileName); string path = System.IO.Path.Combine( Server.MapPath("~http://img.dovov.comprofile"), pic); // file is uploaded file.SaveAs(path); // save the image path path to the database or you can send image // directly to database // in-case if you want to store byte[] ie. for DB using (MemoryStream ms = new MemoryStream()) { file.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); } } // after successfully uploading redirect the user return RedirectToAction("actionname", "controller name"); } 

不过,如果你还想了解更多…试试这篇文章 。

更新1

如果你想用asynchronous方式使用jQuery上传文件,那么试试这篇文章 。

处理服务器端的代码(用于多次上传)是;

  try { HttpFileCollection hfc = HttpContext.Current.Request.Files; string path = "/content/files/contact/"; for (int i = 0; i < hfc.Count; i++) { HttpPostedFile hpf = hfc[i]; if (hpf.ContentLength > 0) { string fileName = ""; if (Request.Browser.Browser == "IE") { fileName = Path.GetFileName(hpf.FileName); } else { fileName = hpf.FileName; } string fullPathWithFileName = path + fileName; hpf.SaveAs(Server.MapPath(fullPathWithFileName)); } } } catch (Exception ex) { throw ex; } 

此控件也返回图像名称(在JavaScriptcallback),然后您可以使用它来在DOM中显示图像。

更新2

或者,您可以尝试MVC 4中的asynchronousfile upload

这里是一个简短的教程:

模型:

 namespace ImageUploadApp.Models { using System; using System.Collections.Generic; public partial class Image { public int ID { get; set; } public string ImagePath { get; set; } } } 

视图:

  1. 创build:

     @model ImageUploadApp.Models.Image @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm("Create", "Image", null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>Image</legend> <div class="editor-label"> @Html.LabelFor(model => model.ImagePath) </div> <div class="editor-field"> <input id="ImagePath" title="Upload a product image" type="file" name="file" /> </div> <p><input type="submit" value="Create" /></p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } 
  2. 索引(用于显示):

     @model IEnumerable<ImageUploadApp.Models.Image> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.ImagePath) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.ImagePath) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Ajax.ActionLink("Delete", "Delete", new {id = item.ID} }) </td> </tr> } </table> 
  3. 控制器(创build)

     public ActionResult Create(Image img, HttpPostedFileBase file) { if (ModelState.IsValid) { if (file != null) { file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName); img.ImagePath = file.FileName; } db.Image.Add(img); db.SaveChanges(); return RedirectToAction("Index"); } return View(img); } 

希望这会帮助:)

  <input type="file" id="picfile" name="picf" /> <input type="text" id="txtName" style="width: 144px;" /> $("#btncatsave").click(function () { var Name = $("#txtName").val(); var formData = new FormData(); var totalFiles = document.getElementById("picfile").files.length; var file = document.getElementById("picfile").files[0]; formData.append("FileUpload", file); formData.append("Name", Name); $.ajax({ type: "POST", url: '/Category_Subcategory/Save_Category', data: formData, dataType: 'json', contentType: false, processData: false, success: function (msg) { alert(msg); }, error: function (error) { alert("errror"); } }); }); [HttpPost] public ActionResult Save_Category() { string Name=Request.Form[1]; if (Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files[0]; } }