增删查改实现多文件上传, 采用ASP.NET MVC 5 and EF 6
Posted null
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了增删查改实现多文件上传, 采用ASP.NET MVC 5 and EF 6相关的知识,希望对你有一定的参考价值。
public class Support { public int SupportId { get; set; } [Required(ErrorMessage="please enter your Name")] [Display(Name="Name")] [MaxLength(100)] public string Name { get; set; } [Required(ErrorMessage="plese enter summary")] [Display(Name="Summary")] [MaxLength(500)] public string Summary { get; set; } public virtual ICollection<FileDetail> FileDetail { get; set; } }
public class FileDetail
{
public Guid Id { get; set; }
public string FileName { get; set; }
public string Extension { get; set; }
public int SupportId { get; set; }
public virtual Support Support { get; set; }
}
public class SupportContext:DbContext
{
public SupportContext()
: base("name=DefaultConnection")
{
}
public DbSet<Support> Supports { get; set; }
public DbSet<FileDetail> FileDetails { get; set; }
}
以上是构建模型和上下文
以下是控制器的相关操作
public class SupportController : Controller { // GET: Support private SupportContext db = new SupportContext(); protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } public ActionResult Index() { return View(db.Supports.ToList()); } public ActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Support support) { if (ModelState.IsValid) { List<FileDetail> fileDetails = new List<FileDetail>(); for (int i = 0; i <Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); FileDetail filedetail = new FileDetail() { FileName = fileName, Extension = Path.GetFileName(fileName), Id = Guid.NewGuid() }; fileDetails.Add(filedetail); var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), filedetail.Id+filedetail.Extension); if (!Directory.Exists(Server.MapPath("~/App_Data/Upload/"))) { // Create the directory it does not exist. Directory.CreateDirectory(Server.MapPath("~/App_Data/Upload/")); } file.SaveAs(path); } } support.FileDetail = fileDetails; db.Supports.Add(support); db.SaveChanges(); return RedirectToAction("Index"); } return View(support); } public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Support support = db.Supports.SingleOrDefault(x=>x.SupportId==id); if (support == null) { return HttpNotFound(); } return View(support); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Support support) { if (ModelState.IsValid) { //new files for (int i = 0; i <Request.Files.Count; i++) { var file=Request.Files[i]; if (file!=null&&file.ContentLength>0) { var fileName = Path.GetFileName(file.FileName); FileDetail fileDetail = new FileDetail() { FileName=fileName, Extension=Path.GetExtension(fileName), Id=Guid.NewGuid(), SupportId=support.SupportId }; var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), fileDetail.Id+fileDetail.Extension); file.SaveAs(path); db.Entry(fileDetail).State =EntityState.Added; } } db.Entry(support).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(support); } //删除文件 public FileResult Download(string p, string d) { return File(Path.Combine(Server.MapPath("~/App_Data/Upload/"),p),System.Net.Mime.MediaTypeNames.Application.Octet,d); } [HttpPost] public JsonResult DeleteFile(string id) { if (string.IsNullOrEmpty(id)) { Response.StatusCode =(int) HttpStatusCode.BadRequest; return Json(new { Result = "Error" }); } try { Guid guid = new Guid(id); FileDetail fileDetail = db.FileDetails.Find(guid); if (fileDetail == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return Json(new { Result = "Error" }); } //Remove from databse db.FileDetails.Remove(fileDetail); db.SaveChanges(); //Delete file from the file system var path = Path.Combine(Server.MapPath("~/App_Data/Upload"), fileDetail.Id + fileDetail.Extension); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } return Json(new { Result = "OK" }); } catch (Exception ex) { return Json(new { Result = "Error", Message = ex.Message }); } } [HttpPost] public JsonResult Delete(int id) { try { Support support = db.Supports.Find(id); if (support == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return Json(new { Result = "Error" }); } //delete files from the file system foreach (var item in support.FileDetail) { string path = Path.Combine(Server.MapPath("~/App_Data/Upload"), item.Id + item.Extension); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } db.Supports.Remove(support); db.SaveChanges(); return Json(new { Result = "OK" }); } catch (Exception ex) { return Json(new { Result="Error",Message=ex.Message}); } } }
index是数据列表 create是添加新的数据记录,edit是编辑更新【此处可以达到效果即上传多个文件】
@{ ViewBag.Title = "Index"; } @model IEnumerable<MultipleFileUpload2.Models.Support> <script src="~/Scripts/jquery-1.10.2.js"></script> <p> @html.ActionLink("Create New", "Create") </p> <table border="1"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Summary) </th> <th>Total Files</th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Summary) </td> <td> @if (item.FileDetail.Count() == 0) { <span>No File</span> } else { <span>@item.FileDetail.Count() File(s)</span> } </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.SupportId }) | <a href="javascript:void(0);" data-id="@item.SupportId" class="deleteItem">Delete</a> </td> </tr> } </table> <script> $(document).ready(function () { $(".deleteItem").click(function (e) { e.preventDefault(); var $ctrl = $(this); if (confirm("Do you really want to delete this item?")) { $.ajax({ url: "/Support/Delete", type: "post", data: { id: $(this).data(\'id\') } }).done(function (data) { if (data.Result = "OK") { $ctrl.closest("tr").remove(); } else if (data.Result.Message) { alert(data.Result.Message); } }).fail(function () { alert("There is something wrong.please try again."); }) } }); }); </script>
@{ ViewBag.Title = "Create"; } @model MultipleFileUpload2.Models.Support <h2>Create</h2> <form action="" method="post" enctype="multipart/form-data"> @Html.AntiForgeryToken() <table> <tr> <td>Name</td> <td><input type="text" name="name" id="name" /></td> </tr> <tr> <td>Summary</td> <td><textarea name="summary"></textarea></td> </tr> <tr> <td>Files</td> <td><input type="file" multiple="multiple" name="file" /></td> </tr> <tr><td colspan="2"><button type="submit">Create</button></td></tr> </table> </form>
@{ ViewBag.Title = "Edit"; } @model MultipleFileUpload2.Models.Support <h2>Edit</h2> <script src="~/Scripts/jquery-1.10.2.js"></script> <form action="/Support/Edit/@Model.SupportId" method="post" enctype="multipart/form-data"> @Html.AntiForgeryToken() @Html.ValidationSummary(true) <table> <tr> <td>Name</td> <input type="hidden" name="supportid" value="@Model.SupportId" /> <td><input type="text" name="name" id="name" value="@Model.Name" /></td> </tr> <tr> <td>Summary</td> <td><textarea name="summary" >@Model.Summary</textarea></td> </tr> <tr> <td>Files</td> <td> <input type="file" multiple="multiple" name="file" /> <ul> @foreach (var item in Model.FileDetail) { <li> <a href="/Support/Download/@(item.Id+item.Extension)">@item.FileName</a> <a href="javascript:void;" data-id="@item.Id" class="deleteItem">删除</a> </li> } </ul> </td> </tr> <tr><td colspan="2"><button type="submit">Save</button></td></tr> </table> </form> <script> $(".deleteItem").click(function (e) { e.preventDefault(); var $ctrl = $(this); if (confirm("Do you reallu want to delete this file?")) { $.ajax({ url: "/Support/DeleteFile", type: "post", data: { id: $(this).data(\'id\')} }).done(function (data) { if (data.Result = "OK") { $ctrl.closest("li").remove(); } else if (data.Result.Message) { alert(data.Result.Message); } }).fail(function () { alert("This is something wrong.Please try again"); }) } }); </script>
原文引用:http://techbrij.com/crud-file-upload-asp-net-mvc-ef-multiple
以上是关于增删查改实现多文件上传, 采用ASP.NET MVC 5 and EF 6的主要内容,如果未能解决你的问题,请参考以下文章