Qualcuno sa di tutorial passo passo su come caricare / visualizzare le immagini da un database utilizzando Entity Framework? Ho controllato frammenti di codice, ma non sono ancora chiaro su come funziona. Non ho il codice, perché oltre a scrivere un modulo di caricamento, sono perso. Qualsiasi aiuto (e intendo qualsiasi) è molto apprezzato.
In un sidenote, perché nessun libro copre questo argomento? Ho sia Pro ASP.NET MVC 4 e Professional MVC4, e non ne fanno menzione.
Dai un’occhiata al mio articolo sul caricamento dell’immagine o puoi usare lo stesso codice descritto di seguito;
il tuo codice di visualizzazione;
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { }
il tuo controller dovrebbe avere un metodo di azione che accetti HttpPostedFileBase
;
public ActionResult FileUpload(HttpPostedFileBase file) { if (file != null) { string pic = System.IO.Path.GetFileName(file.FileName); string path = System.IO.Path.Combine( Server.MapPath("~/images/profile"), 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"); }
Tuttavia, se vuoi ancora saperne di più … prova questo articolo .
Aggiornamento 1
Nel caso in cui desideri caricare file usando jQuery con asincronismo, prova questo articolo .
il codice per gestire il lato server (per il caricamento multiplo) è;
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; }
questo controllo restituisce anche il nome dell’immagine (in una chiamata javascript) che quindi è ansible utilizzarlo per visualizzare l’immagine nel DOM.
In alternativa, puoi provare i caricamenti di file asincroni in MVC 4 .
Ecco un breve tutorial:
Modello:
namespace ImageUploadApp.Models { using System; using System.Collections.Generic; public partial class Image { public int ID { get; set; } public string ImagePath { get; set; } } }
Vista:
Creare:
@model ImageUploadApp.Models.Image @{ ViewBag.Title = "Create"; } Create
@using (Html.BeginForm("Create", "Image", null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) } @Html.ActionLink("Back to List", "Index") @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Indice (per display):
@model IEnumerable @{ ViewBag.Title = "Index"; } Index
@Html.ActionLink("Create New", "Create")
@Html.DisplayNameFor(model => model.ImagePath) @foreach (var item in Model) { @Html.DisplayFor(modelItem => item.ImagePath) @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Ajax.ActionLink("Delete", "Delete", new {id = item.ID} }) }
Controller (Crea)
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); }
Spero che questo aiuterà 🙂
$("#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]; } }