Uploading Files in MVC
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using UploadingFilesinMVC.Models; namespace UploadingFilesinMVC.Controllers { public class FileController : Controller { private FileUploadEntities db = new FileUploadEntities(); public ActionResult Files() { return View(db.tblFiles.ToList()); } [HttpPost] public ActionResult Files(HttpPostedFileBase postedFile) { try { byte[] bytes; using (BinaryReader br = new BinaryReader(postedFile.InputStream)) { bytes = br.ReadBytes(postedFile.ContentLength); } tblFile tb = new tblFile(); tb.Name = postedFile.FileName; tb.data = bytes; tb.contenttype = postedFile.ContentType; db.tblFiles.Add(tb); db.SaveChanges(); return RedirectToAction("Files"); } catch(Exception ex) { throw ex; } } [HttpPost] public FileResult DownloadFile(int? fileId) { byte[] bytes; string fileName, contentType; var data = db.tblFiles.Find(fileId); bytes = (byte[])data.data; contentType = data.contenttype; fileName = data.Name; return File(bytes, contentType, fileName); } [HttpPost] public FileResult DownloadFile(int? fileId) { tblFile tblfile = db.tblFiles.Find(fileId); //string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString; //using (SqlConnection con = new SqlConnection(constr)) //{ // using (SqlCommand cmd = new SqlCommand()) // { // cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id"; // cmd.Parameters.AddWithValue("@Id", fileId); // cmd.Connection = con; // con.Open(); // using (SqlDataReader sdr = cmd.ExecuteReader()) // { // sdr.Read(); // bytes = (byte[])sdr["Data"]; // contentType = sdr["ContentType"].ToString(); // fileName = sdr["Name"].ToString(); // } // con.Close(); // } //} return File(tblfile.data, tblfile.contenttype, tblfile.Name); } // GET: /File/ public ActionResult Index() { return View(db.tblFiles.ToList()); } // GET: /File/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } tblFile tblfile = db.tblFiles.Find(id); if (tblfile == null) { return HttpNotFound(); } return View(tblfile); } // GET: /File/Create public ActionResult Create() { return View(); } // POST: /File/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include="id,Name,contenttype,data")] tblFile tblfile) { if (ModelState.IsValid) { db.tblFiles.Add(tblfile); db.SaveChanges(); return RedirectToAction("Index"); } return View(tblfile); } // GET: /File/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } tblFile tblfile = db.tblFiles.Find(id); if (tblfile == null) { return HttpNotFound(); } return View(tblfile); } // POST: /File/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include="id,Name,contenttype,data")] tblFile tblfile) { if (ModelState.IsValid) { db.Entry(tblfile).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(tblfile); } // GET: /File/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } tblFile tblfile = db.tblFiles.Find(id); if (tblfile == null) { return HttpNotFound(); } return View(tblfile); } // POST: /File/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { tblFile tblfile = db.tblFiles.Find(id); db.tblFiles.Remove(tblfile); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } Views: Files.html @model IEnumerable@{ ViewBag.Title = "Files"; }
Files
Index @using (Html.BeginForm("Files", "File", FormMethod.Post, new { enctype = "multipart/form-data" })) { } @using (Html.BeginForm("DownloadFile", "File", FormMethod.Post)) { }
Index.html @model IEnumerable
@if(Model.Count() > 0) { foreach (var file in Model) { File ID File Name Download } } else { @file.id @file.Name Download } @{ ViewBag.Title = "Index"; } Index
@Html.ActionLink("Create New", "Create")
@foreach (var item in Model) { }Details.cshtml @model IEnumerable
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.contenttype) @Html.DisplayNameFor(model => model.data) @Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.contenttype) @Html.DisplayFor(modelItem => item.data) @Html.ActionLink("Edit", "Edit", new { id=item.id }) | @Html.ActionLink("Details", "Details", new { id=item.id }) | @Html.ActionLink("Delete", "Delete", new { id=item.id }) @{ ViewBag.Title = "Index"; } Index
@Html.ActionLink("Create New", "Create")
@foreach (var item in Model) { }Create.cshtml @model UploadingFilesinMVC.Models.tblFile @{ ViewBag.Title = "Create"; }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.contenttype) @Html.DisplayNameFor(model => model.data) @Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.contenttype) @Html.DisplayFor(modelItem => item.data) @Html.ActionLink("Edit", "Edit", new { id=item.id }) | @Html.ActionLink("Details", "Details", new { id=item.id }) | @Html.ActionLink("Delete", "Delete", new { id=item.id }) Create
@using (Html.BeginForm()) { @Html.AntiForgeryToken()}tblFile
@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)@Html.LabelFor(model => model.contenttype, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.contenttype) @Html.ValidationMessageFor(model => model.contenttype)@Html.LabelFor(model => model.data, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.data) @Html.ValidationMessageFor(model => model.data)@Html.ActionLink("Back to List", "Index")@section Scripts { @Scripts.Render("~/bundles/jqueryval") } Edit.cshtml @model UploadingFilesinMVC.Models.tblFile @{ ViewBag.Title = "Edit"; }Edit
@using (Html.BeginForm()) { @Html.AntiForgeryToken()}tblFile
@Html.ValidationSummary(true) @Html.HiddenFor(model => model.id)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)@Html.LabelFor(model => model.contenttype, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.contenttype) @Html.ValidationMessageFor(model => model.contenttype)@Html.LabelFor(model => model.data, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.data) @Html.ValidationMessageFor(model => model.data)@Html.ActionLink("Back to List", "Index")@section Scripts { @Scripts.Render("~/bundles/jqueryval") } Delete.cshtml @model UploadingFilesinMVC.Models.tblFile @{ ViewBag.Title = "Delete"; }Delete
Are you sure you want to delete this?
tblFile
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
- @Html.DisplayNameFor(model => model.Name)
- @Html.DisplayFor(model => model.Name)
- @Html.DisplayNameFor(model => model.contenttype)
- @Html.DisplayFor(model => model.contenttype)
- @Html.DisplayNameFor(model => model.data)
- @Html.DisplayFor(model => model.data)
| @Html.ActionLink("Back to List", "Index")}
Partial Views in MVC
Include Function
Using Cookies
Update Multiple Items
Edit,Update Multiple Items
Uploading Files in MVC