sábado, 3 de diciembre de 2011

Cargar y guardar una imagen en la base de datos

8 comentarios:
Para este ejemplo utilizaremos la base de datos Nortwind con la tabla categories.



1.) Debemos crear el campo  MimeType para almacenar el tipo de datos del archivo.


ALTER TABLE dbo.Categories ADD
ImageMimeType varchar(50) NULL


Pero en este ejemplo no utilizaremos ya que lo realizaremos con Entity Framework.

2.) Crear el proyecto, File - New Proyect - ASP.NET MVC Web Applicaction



3.)Le mostrara la pantalla de que tipo de aplicación (Internet o intranet), que tipo de motor quiere utilizar ASPX o Razor. Seleccione Internet Application y Use HTML 5 semantic Markup.



4.) En el Solucion explorer, presione clic derecho sobre la carpeta Models y luego en la ventana seleccione Ado Entity Data Model, con el nombre: NorthwindModel.edmx

Seleccione las tablas: Orders, Customers, Employees





5.) Agregaremos el controlador de Categorias.


5.1) Presione Clic derecho sobre la carpeta de Controllers, luego add y por ultimo Controller....




4.2) Se mostrara la pantalla para que seleccione el tipo de Controller.




Nombre: CategoriasController
Template: Adding a controller with read/write actions and views, using Entity Framework 
Model Data Class: Categories (Nombre proyecto.Models)
Data Context class: NortwindEntities (Nombre proyecto.Models)
Views: Razor (cshtml)


5.) Explorado las Vistas.


Luego del ultimo paso nos creo 5 archivos en la carpeta view, estos archivos nos ayudaran a manejar nuestro controlador.


Create.cshtml
Delete.cshtml
Details.cshtml
Edit.cshtml
Index.cshtml



6.) Abra el controlador : CategoriasController

6.1)Agregue el siguiente método

 public FileContentResult GetImage(Int32 CategoryID) 
        { 
            Category cat = db.Categories.FirstOrDefault(c => c.CategoryID == CategoryID); 
            if (cat != null)
            { 
                 
                string type = string.Empty;
                if (!string.IsNullOrEmpty(cat.ImageMimeType)) 
                { 
                    type = cat.ImageMimeType; 
                } 
                else 
                { 
                    type = "image/jpeg"; 
                } 

                return File(cat.Picture, type); 
            } 
            else 
            { 
                return null;
            } 
        }

6.2) Edite el metodo Create de la siguiente manera.

  [HttpPost] 
        public ActionResult Create(Category category, HttpPostedFileBase image)
        { 
            if (ModelState.IsValid) 
            { 
                if (image != null)
                {                 
                    category.ImageMimeType = image.ContentType; 
                    int length = image.ContentLength; 
                    byte[] buffer = new byte[length]; 
                    image.InputStream.Read(buffer, 0, length);
                    category.Picture = buffer; 
                } 

                db.Categories.AddObject(category); 
                db.SaveChanges(); 
                return RedirectToAction("Index");   
            } 

            return View(category); 
        }

7.) Editando vistas
7.1) Abra la vista index.cshtml ubicada en la carpeta view, agregue el siguiente código, después del td del campo descripción.

<td> 
@if (item.Picture != null)
{ 
<div style="float:left;margin-right:20px"> 
<img width="75" height="75" src="@Url.Action("GetImage", "Categorias", new { item.CategoryID })" /> 
</div> 
} 
</td>

7.2)Abra la vista Create.cshtml ubicada en la carpeta view, reemplace con el siguiente código:

 @model MVCentity.Models.Category 

@{ 
    ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

@using (Html.BeginForm("Create", "Categorias", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.ValidationSummary(true) 
    <fieldset> 
        <legend>Category</legend> 

        <div class="editor-label"> 
            @Html.LabelFor(model => model.CategoryName) 
        </div> 
        <div class="editor-field"> 
            @Html.EditorFor(model => model.CategoryName) 
            @Html.ValidationMessageFor(model => model.CategoryName) 
        </div> 

        <div class="editor-label"> 
            @Html.LabelFor(model => model.Description) 
        </div> 
        <div class="editor-field"> 
            @Html.EditorFor(model => model.Description) 
            @Html.ValidationMessageFor(model => model.Description) 
        </div> 
        <div class="editor-label"> 
            Imagen 
        </div> 
        <div class="editor-field"> 
            <input type="file" name="image" /> 
        </div> 
        <p> 
            <input type="submit" value="Create" /> 
        </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div>
Ver