✎

Fonte originale

[Articolo originale](https://www.mikesdotnetting.com/article/259/asp-net-mvc-5-with-ef-6-working-with-files)

1. Creare un tipo enumerativo che specifichi il tipo di file che verrà caricato

Per maggiore semplicità verrà creato un enumerativo che vada ad indicare l'utilizzo di ogni file che possa essere caricato.

1namespace solution.Models2{3   public enum FileType4   {5      Avatar = 1, Photo6   }7}

2. Creare un'entità File

Nelle ultime versioni di SQL Server è possibile archiviare dati di tipo FileStream, ma la versione di Entity Framework 6.1.2 ancora non supporta questo tipo di dato, inoltre quando vengono archiviati i dati sul DB, questi vengono salvati in formato binario (rappresentato da un array di byte), quindi utilizzeremo questo approccio.

1using System.ComponentModel.DataAnnotations;23namespace solution.Models4{5   public class File6   {7      public int FileId { get; set; }8      [StringLength(255)]9      public string FileName { get; set; }10      [StringLength(100)]11      public string ContentType { get; set; }12      public byte[] Content { get; set; }13      public FileType FileType { get; set; }14      public int PersonId { get; set; }15      public virtual Person Person { get; set; }16   }17}

3. Creare un'entità File

1using System.ComponentModel.DataAnnotations;2using System.ComponentModel.DataAnnotations.Schema;3using System.Collections.Generic;45namespace ContosoUniversity.Models6{7   public abstract class Person8   {9      public int ID { get; set; }1011      [Required]12      [StringLength(50)]13      [Display(Name = "Last Name")]14      public string LastName { get; set; }15      [Required]16      [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]17      [Column("FirstName")]18      [Display(Name = "First Name")]19      public string FirstMidName { get; set; }2021      [Display(Name = "Full Name")]22      public string FullName23      {24         get25         {26            return LastName + ", " + FirstMidName;27         }28      }29      public virtual ICollection<File> Files { get; set; }30   }31}

4. Aggiungere un DbSet al Context

1public DbSet<File> Files { get; set; }

5. Modificare il form di Creazione

1→@using (Html.BeginForm("Create", "Student", null, FormMethod.Post, new {enctype = "multipart/form-data"}))2{3   @Html.AntiForgeryToken()45   <div class="form-horizontal">6      <h4>Student</h4>7      <hr />8      @Html.ValidationSummary(true, "", new { @class = "text-danger" })9      <div class="form-group">10         @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })11         <div class="col-md-10">12            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })13            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })14         </div>15      </div>1617      <div class="form-group">18         @Html.LabelFor(model => model.FirstMidName, htmlAttributes: new { @class = "control-label col-md-2" })19         <div class="col-md-10">20            @Html.EditorFor(model => model.FirstMidName, new { htmlAttributes = new { @class = "form-control" } })21            @Html.ValidationMessageFor(model => model.FirstMidName, "", new { @class = "text-danger" })22         </div>23      </div>2425      <div class="form-group">26         @Html.LabelFor(model => model.EnrollmentDate, htmlAttributes: new { @class = "control-label col-md-2" })27         <div class="col-md-10">28            @Html.EditorFor(model => model.EnrollmentDate, new { htmlAttributes = new { @class = "form-control" } })29            @Html.ValidationMessageFor(model => model.EnrollmentDate, "", new { @class = "text-danger" })30         </div>31      </div>3233      <div class="form-group">34         @Html.Label("Avatar", new {@class = "control-label col-md-2"})35         <div class="col-md-10">36            <input type="file" id="Avatar" name="upload" />37         </div>38      </div>3940      <div class="form-group">41         <div class="col-md-offset-2 col-md-10">42            <input type="submit" value="Create" class="btn btn-default" />43         </div>44      </div>45   </div>46}

6. Modificare il Controller

Specificare il tipo di elemento "File". Comunque questo non è sufficiente per assicurare che il file sia correttamente caricato sul server. E' importante utilizzare anche uno degli overload dell'helper Html.BeginForm per aggiungere l'attributo enctype ed impostare il valore a "multipart/form-data". Questo è un passaggio importante perché la procedura di upload funzioni correttamente.

Aggiungere al metodo HttpPost Create del Controller

1[HttpPost]2[ValidateAntiForgeryToken]3public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate")]Student student, HttpPostedFileBase upload)4{5   try6   {7      if (ModelState.IsValid)8      {9         if (upload != null && upload.ContentLength > 0)10         {11            var avatar = new File12            {13            FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType };1415            using (var reader = new System.IO.BinaryReader(upload.InputStream))16            {17               avatar.Content = reader.ReadBytes(upload.ContentLength);18            }1920            student.Files = new List<File> { avatar };21         }2223         db.Students.Add(student);24         db.SaveChanges();2526         return RedirectToAction("Index");27      }28   }29   catch (RetryLimitExceededException /* dex */)30   {31      //Log the error (uncomment dex variable name and add a line here to write a log.32      ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");33   }3435   return View(student);36   }37}

Il primo passaggio aggiunge un nuovo parametro alla firma del metodo Create - upload che è un'istanza del tipo HttpPostedFileBase. Il nome del parametro corrisponde al nome del valore dell'attributo dell'input type="file" nel form Create in questo modo il binder di MVC è in grado di associare il file caricato al parametro che si è aggiunto al metodo Create.

The highlighted code block that you added is responsible for extracting the binary data from the request and populating a new File entity instance ready to be added to the student's Files collection. If the user adds a new student without uploading a file, the upload parameter will equate to null, which is why that condition is checked before any attempt to access the HttpPostedFileBase ContentLength property. If you do not perform this check, and then reference the ContentLength property when no file has been uploaded, an exception will be raised. You then check the ContentLength because it is perfectly possible to upload an empty file. If the user does that, the ContentLength property will return 0, and there is no point in storing a file with no data in it. If the upload passes both tests, you create a new File object and assign the relevant properties with values taken from the upload parameter. The binary data is obtained from the InputStream property of the uploaded file, and a BinaryReader object is used to read that into the Content property of the File object. Finally, you add the new File object to the student object.

7. Modificare il method Detail

Having stored the image in the database, you need to make some alterations to obtain the image and display it in the Details view. First, you will use the Include method in the LINQ query that fetches the student from the database to bring back releated files. The Include method does not support filtering, so the highlighted line below fetches all files associated with the student regardless of type.

1public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = db.Students.Include(s => s.Files).SingleOrDefault(s => s.ID == id); if (student == null) { return HttpNotFound(); } return View(student); }

Add the highlighted line to the Views\web.config file. Make sure you add this to the web.config file in the Views directory - not the one in the root folder.

1<namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization"/> <add namespace="System.Web.Routing" /> <add namespace="ContosoUniversity" /> <add namespace="ContosoUniversity.Models" /> </namespaces>

Add the highlighted section of code to the Views\Student\Details.cshtml file.

1<h4>Student</h4> <hr /> <dl class="dl-horizontal"> @if(Model.Files.Any(f => f.FileType == FileType.Avatar)){ <dt> Avatar </dt> <dd> <img src="~/File?id=@Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" /> </dd> } <dt> @Html.DisplayNameFor(model => model.LastName) </dt>

The change that you made to the Views\web.config file makes the ContosoUniversity.Model namespace available to your views. It results in you not having to use the fully qualified name to reference items in that namespace, such as the FileType enumeration. If you had not made that change, you would have to do a bit more typing in the view whenever you want to reference types in the Model namespace: @if(Model.Files.Any(f => f.FileType == ContosoUniversity.Model.FileType.Avatar)){ You returned all of the files associated with the student (if there are any), so you must check to see if there are any files matching the Avatar file type. If there are, you render the first of these files. The image is rendered using a standard HTML img tag. By convention, the url of the image maps to the Index method of a controller called File, passing in the id of the file as a query string value.

8. Aggiungere il controller File

Una cosa importante da segnalare è che nelle ultime versioni di SQL Server è possibile archiviare Newer versions of SQL Server offer the FileStream data type for storing file data. Existing versions of Entity Framework (6.1.2 as of the publication date of this tutorial) do not support the FileStream data type via Code First. When you store file content in a database, the content itself is stored in binary format. This is represented as an array of bytes in .NET which Entity Framework (currently) maps to the SQL Server varbinary(max) data type.

1using ContosoUniversity.DAL; using System.Web.Mvc; namespace ContosoUniversity.Controllers { public class FileController : Controller { private SchoolContext db = new SchoolContext(); // // GET: /File/ public ActionResult Index(int id) { var fileToRetrieve = db.Files.Find(id); return File(fileToRetrieve.Content, fileToRetrieve.ContentType); } } }

Alter the Views\Student\Edit.cshtml file to include the correct enctype attribute in the form, and to both display the existing image and to provide a file upload should the user wish to provide a replacement:

1@using (Html.BeginForm("Edit", "Student", null, FormMethod.Post, new {enctype = "multipart/form-data"})) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Student</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.ID) <div class="form-group"> @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.FirstMidName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.FirstMidName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FirstMidName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EnrollmentDate, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.EnrollmentDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.EnrollmentDate, "", new { @class = "text-danger" }) </div> </div> @if(Model.Files.Any(f => f.FileType == FileType.Avatar)) { <div class="form-group"> Current Avatar <div class="col-md-10"> <img src="~/File?id=@Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" /> </div> </div> } <div class="form-group"> @Html.Label("Avatar", new {@class = "control-label col-md-2"}) <div class="col-md-10"> <input type="file" id="Avatar" name="upload" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> }

Make the highlighted changes to the HttpPost Edit method as shown below.

1[HttpPost, ActionName("Edit")] [ValidateAntiForgeryToken] public ActionResult EditPost(int? id, HttpPostedFileBase upload) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var studentToUpdate = db.Students.Find(id); if (TryUpdateModel(studentToUpdate, "", new string[] { "LastName", "FirstMidName", "EnrollmentDate" })) { try { if (upload != null && upload.ContentLength > 0) { if (studentToUpdate.Files.Any(f => f.FileType == FileType.Avatar)) { db.Files.Remove(studentToUpdate.Files.First(f => f.FileType == FileType.Avatar)); } var avatar = new File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } studentToUpdate.Files = new List<File> { avatar }; } db.Entry(studentToUpdate).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } catch (RetryLimitExceededException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator."); } } return View(studentToUpdate); }

You altered the signature of the HttpPost Edit method to accept an instance of the HttpPostedFile. As in the Create method, this represents the uploaded file. The highlighted code block checks to see if a file was uploaded, and if one was, that it contains data. These are the same checks as you made in the Create method. If the file contains data, you find any existing files associated with the current student that are Avatar file types. If found, you mark the file for deletion. Then you add the uploaded file as a replacement.

9. Personalizzare il metodo Edit e la View

Alter the code in the HttpGet Edit method in the StudentController to include the retrieval of files as in the highlighted code below.

1// GET: Student/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = db.Students.Include(s => s.Files).SingleOrDefault(s => s.ID == id); if (student == null) { return HttpNotFound(); } return View(student); }