Click here to Skip to main content
15,910,471 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to save images to a database but it is not picking up the image, I have it defined as byte[], here is my model

C#
namespace ShoppingCart.Models
{
    public class Image
    {
        public int ImageId { get; set; }
        public int ItemId { get; set; }
        public string name { get; set; }
        public byte[] Images { get; set; }


        public virtual Item Item { get; set; }
    }
}


Here is the controller

C#
namespace ShoppingCart.Controllers
{
    public class ImageController : Controller
    {
        private ShoppingCartContext db = new ShoppingCartContext();

        //
        // GET: /Image/

        public ActionResult Index()
        {
            var images = db.Images.Include(i => i.Item);
            return View(images.ToList());
        }

        //
        // GET: /Image/Details/5

        public ActionResult Details(int id = 0)
        {
            Image image = db.Images.Find(id);
            if (image == null)
            {
                return HttpNotFound();
            }
            return View(image);
        }

        //
        // GET: /Image/Create

        public ActionResult Create()
        {
            ViewBag.ItemId = new SelectList(db.Items, "ItemID", "Title");
            return View();
        }

        //
        // POST: /Image/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Image image)
        {
            if (ModelState.IsValid)
            {
                db.Images.Add(image);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ItemId = new SelectList(db.Items, "ItemID", "Title", image.ItemId);
            return View(image);
        }

        //
        // GET: /Image/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Image image = db.Images.Find(id);
            if (image == null)
            {
                return HttpNotFound();
            }
            ViewBag.ItemId = new SelectList(db.Items, "ItemID", "Title", image.ItemId);
            return View(image);
        }

        //
        // POST: /Image/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Image image)
        {
            if (ModelState.IsValid)
            {
                db.Entry(image).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ItemId = new SelectList(db.Items, "ItemID", "Title", image.ItemId);
            return View(image);
        }

         
        [HttpPost]
         public ActionResult UploadImages(HttpPostedFileBase[] uploadImages)
        {
            if (uploadImages.Count() <= 1)
             {
            return RedirectToAction("Index");
             }

        foreach (var image in uploadImages)
        {
            if (image.ContentLength > 0)
            {
                byte[] imageData = null;
                using (var binaryReader = new BinaryReader(image.InputStream))
                {
                    imageData = binaryReader.ReadBytes(image.ContentLength);
                }
                var headerImage = new Image
                {
                    Images = imageData,
                    name = image.FileName,

                };
                db.Entry(headerImage).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
        return RedirectToAction("Index");
    }

        //
        // GET: /Image/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Image image = db.Images.Find(id);
            if (image == null)
            {
                return HttpNotFound();
            }
            return View(image);
        }

        //
        // POST: /Image/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Image image = db.Images.Find(id);
            db.Images.Remove(image);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


and this is my view:

C#
@model ShoppingCart.Models.Image

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Image</legend>

        @Html.HiddenFor(model => model.ImageId)

        <div class="editor-label">
            @Html.LabelFor(model => model.ItemId, "Item")
        </div>
        <div class="editor-field">
            @Html.DropDownList("ItemId", String.Empty)
            @Html.ValidationMessageFor(model => model.ItemId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.name)
            @Html.ValidationMessageFor(model => model.name)
        </div>
        
                <div class="editor-field">
                    <span class="span4">
                        <input type="file" name="Images" multiple="multiple" class="input-files"/>
                    </span>
                    
                </div>
            
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Posted
Comments
TryAndSucceed 7-Oct-13 14:38pm    
So, is it giving you any exception?
[no name] 7-Oct-13 15:27pm    
No, it just doesnt save anything to the database. it skips the whole ActionResult UploadImages
TryAndSucceed 7-Oct-13 15:50pm    
The problem is, your save button is redirecting to Edit(Post). You need to call Upload Images method in Edit Post whenever a file is attached. Or create another Button which says Upload and call the Upload method whenever that button is hit.

1 solution

Have you seen the example in this article?
Storing images in SQL Server using EF and ASP.NET[^]

It contains a ASP.NET MVC 4 Example project and a ASP.NET WebForms example project.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900