'(C#) How do I send an image file from an ASP.NET MVC 5 web form to my SQL database?

I'm trying to insert an image file that a user uploads from a web form into my SQL database so that it shows up on my Index page next to their information. All of the other information sends and shows up on the page, but the photo simply won't save to the database or display on the Index. Could someone help me figure out what I have wrong?

FacultyController.cs

using POS.Datos;
using POS.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.IO ;

namespace POS.Controllers
{
    public class FacultyController : Controller
    {
        FacultyAdmin admin = new FacultyAdmin();

        // GET: Faculty
        public ActionResult Index()
        {
            return View(admin.Consultar());
        }

        [HttpGet]
        public ActionResult Nuevo()
        {
            ViewBag.Meal_Plan = GetPlanesSelect();
            admin.Consultar();
            return View();
        }

        [HttpPost]
        [ActionName("Guardar")]
        public ActionResult NuevoPost(Faculty empleado)
        {
            if (ModelState.IsValid)
                {
                Cafeteria_POSEntities context = new Cafeteria_POSEntities();
                admin.Consultar();
                context.Faculties.Add(empleado);
                context.SaveChanges();
                ViewBag.mensaje = "Informacion Guardada";
                return RedirectToAction("Index");
                }
            return View(empleado);
        }
        
        public ActionResult Guardar() // HTTP GET
        {
            ViewBag.mensaje = "";
            ViewBag.Meal_Plan = GetPlanesSelect();
            return View();
        }

        [HttpGet]
        public ActionResult Editar(int id)
        {
            Cafeteria_POSEntities context = new Cafeteria_POSEntities();
            Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
            ViewBag.Meal_Plan = GetPlanesSelect();
            return View(empleado);
        }

        [HttpPost]
        [ActionName("Editar")]
        public ActionResult Editar(Faculty empleado)
        {
            if (ModelState.IsValid)
            {
                Cafeteria_POSEntities context = new Cafeteria_POSEntities();
                context.Entry(empleado).State = EntityState.Modified;
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(empleado);

        }

        public IEnumerable<SelectListItem> GetPlanesSelect()
        {
            using (Cafeteria_POSEntities Context = new Cafeteria_POSEntities())
            {
                return Context.Plans.Select(plan => new SelectListItem { Value = plan.Plan_Name, Text = plan.Plan_Name }).ToList();
            }
        }

        [HttpGet]
        public ActionResult Eliminar(int id)
        {
            Cafeteria_POSEntities context = new Cafeteria_POSEntities();
            Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
            return View(empleado);
        }

        [HttpPost]
        [ActionName("Eliminar")]
        public ActionResult EliminarConfirm(int id)
        {
            Cafeteria_POSEntities context = new Cafeteria_POSEntities();
            Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
            context.Faculties.Remove(empleado);
            context.SaveChanges();

            return RedirectToAction("Index");
        }

        // Saves user-uploaded image to the database //
        public string Upload_Image(HttpPostedFileBase image_file)
            {
            Random r = new Random() ;
            String path = "-1" ;
            int random = r.Next() ;
            if (image_file != null && image_file.ContentLength > 0)
                {
                string extension = Path.GetExtension(image_file.FileName) ;
                if (extension.ToLower().Equals(".jpg") || extension.ToLower().Equals(".jpeg") || extension.ToLower().Equals(".png"))
                    {
                    try
                        {
                        path = Path.Combine(Server.MapPath("~/Content/Images") , random + Path.GetFileName(image_file.FileName)) ;
                        image_file.SaveAs(path) ;
                        path = "~/Content/Images/" + random + Path.GetFileName(image_file.FileName) ;
                        }
                    catch (Exception ex)
                        {
                        path = "-1" ;
                        }
                    }
                else
                    {
                    Response.Write("<script>alert('Images may only be of the following formats: .jpg , .jpeg , and .png .');</script>") ;
                    }
                }
            else 
                {
                Response.Write("<script>alert('Please select an image to upload!');</script>");
                path = "-1" ;
                }
        
            return path ;
            }
    } 
}

Faculty.cs

namespace POS.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;

    public partial class Faculty
    {
        [DisplayName("Employee ID:")]
        public int Employee_ID { get; set; }
    
        [DisplayName("Organization Name:")]
        public string Organization_Name { get; set; }
        
        [DisplayName("First Name:")]
        public string First_Name { get; set; }
    
        [DisplayName("Last Name:")]
        public string Last_Name { get; set; }
    
        [DisplayName("Job Title:")]
        public string Job_Title { get; set; }
    
        [DisplayName("Email:")]
        public string Email { get; set; }
    
        [DisplayName("Photo:")]
        public byte[] Photo { get; set; }
    
        [DisplayName("Address:")]
        public string Address { get; set; }
    
        [DisplayName("Phone Number:")]
        public string Phone_Number { get; set; }
    
        [DisplayName("Meal Plan:")] 
        public string Meal_Plan { get; set; }
    
        [DisplayName("Meal Plan Status:")]
        public bool Meal_Plan_Status { get; set; }
    
        [DisplayName("Plan:")]
        public virtual Plan Plan { get; set; }
    }

}

Guardar.cshtml

@model POS.Models.Faculty

@{
ViewBag.Title = "Add Faculty Member";
}

<h2>Faculty Member</h2>
<h4>Add a new faculty member</h4>
<!-- Metodo "Nuevo", Controlador "Producto", Accion "HTTP POST" -->
@using (Html.BeginForm("Guardar", "Faculty", FormMethod.Post , new {enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            <label class="control-label col-md-2" for="Organization_Name">Organization Name</label>
            <div class="col-md-10">
                @Html.EditorFor(model => model.Organization_Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Organization_Name, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.First_Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10" for="First_Name">
                @Html.EditorFor(model => model.First_Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.First_Name, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Last_Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Last_Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Last_Name, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Job_Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Job_Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Job_Title, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Photo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Photo, "", new { @class = "text-danger" })
                <input type="file" id="image_file" name="file"/>
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Phone_Number, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Phone_Number, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Phone_Number, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Meal_Plan, "Meal_Plan", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Meal_Plan", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Meal_Plan, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Meal_Plan_Status, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Meal_Plan_Status)
                    @Html.ValidationMessageFor(model => model.Meal_Plan_Status, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
    
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Guardar" class="btn btn-default" />
            </div>
        </div>
    
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <font color="green">@ViewBag.mensaje</font>
            </div>
        </div>
    </div>

}

<!--

    
        <h4><b>Personal Information</b></h4>
        
            Name: 
            
            
            
            
                Email Address: 
                
            
            <!--
            Date of Birth: 
            

-->
<!--
    
        Gender: 
        
        Male
        
        Female
    



    
        Phone Number:
        
    
    Address (Optional): 
    
    
    
    
    
    <h4><b>Institutional Information</b></h4>
    
        Organization: 
        
            
            Language Institute
            Keiser University
        
        <br />
        Job Title: 
        
            
            Administrator
            Cafeteria Team Member
            Cleaning Crew Team Member
            Coach
            Instructor
            I.T. Team Member
            Library Team Member
            Security Guard
        
        <br />
        Meal Plan: 
        
            
            No Plan
            A
            B
            C
        
        Active?
        
    
    
        
            
        
    

-->

@Html.ActionLink("Return to Faculty Index", "Index")

@section Scripts {
@Scripts.Render("\~/bundles/jqueryval")
}

The Faculty table in my database

I've already tried going through this video (https://www.youtube.com/watch?v=-jNWVKoYhaM), but, for some reason, it still doesn't work (though I can now save images to ~/Content/Images and the program actually seems like it wants to pull an image from said file).



Solution 1:[1]

You're storing the images to a folder on your server, which is fine. But you also seem to expect the image file to be stored in the database as well. If you're going to store the image files in the file system and not in the database then what you really want in the database is the path to the image file so you can reference that in the HTML. As you are writing the photo to the file system you should also update the database with the path to the file and then in your HTML you can generate an <img> tag to load the file from the file system.

You should update the db during Upload_Image(). Currently it's only saving the image file to the file system.

try
    {
    path = Path.Combine(Server.MapPath("~/Content/Images") , random + Path.GetFileName(image_file.FileName)) ;
    image_file.SaveAs(path) ;
    /* SAVE path TO DB HERE */
    }
catch (Exception ex)
    {
    path = "-1" ;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1