How to save an image to Database using MVC 4

前端 未结 1 604
情书的邮戳
情书的邮戳 2020-12-07 15:28

So I have a project which is a Shopping Cart, I have to save images to the database instead of uploading them to the server, here is my model

namespace Shopp         


        
1条回答
  •  囚心锁ツ
    2020-12-07 15:55

    There are two easy ways to do images -- one is to simply return the image itself in the controller:

        [HttpGet]
        [AllowAnonymous]
        public ActionResult ViewImage(int id)
        {
            var item = _shoppingCartRepository.GetItem(id);
            byte[] buffer = item.Picture;
            return File(buffer, "image/jpg", string.Format("{0}.jpg", id));
        }
    

    And the view would just reference it:

        
    

    Additionally, you can include it in the ViewModel:

        viewModel.ImageToShow = Convert.ToBase64String(item.Picture);
    

    and in the view:

        @Html.Raw("");
    

    For the data-store, you would simply use a byte array (varbinary(max)) or blob or any compatible type.

    Uploading images

    Here, an object called HeaderImage is an EntityFramework EntityObject. The controller would look something like:

        [HttpPost]
        public ActionResult UploadImages(HttpPostedFileBase[] uploadImages)
        {
            if (uploadImages.Count() <= 1)
            {
                return RedirectToAction("BrowseImages");
            }
    
            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 HeaderImage
                    {
                        ImageData = imageData,
                        ImageName = image.FileName,
                        IsActive = true
                    };
                    imageRepository.AddHeaderImage(headerImage);
                }
            }
            return RedirectToAction("BrowseImages");
        }
    

    The View would look something like:

                @using (Html.BeginForm("UploadImages", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
                {
                    
    }

    0 讨论(0)
提交回复
热议问题