How to save and retrieve image bytes in ASP.NET MVC
Microsoft Net Framework

Step-1) Create database table like

CREATE TABLE [dbo].[LuckyDrawHistory](

       [LuckyDrawHistoryId] [bigint] IDENTITY(1,1) NOT NULL,

       [LuckyDrawDate] [datetime] NULL,

       [Description] [nvarchar](max) NULL,

       [ImageName] [nvarchar](max) NULL,

       [ImageBytes] [image] NULL,

 CONSTRAINT [PK_LuckyDrawHistory] PRIMARY KEY CLUSTERED

([LuckyDrawHistoryId] ASC ))

 

Step-2) In MVC view

//To show already saved image or default image

@{

    string imgDataURL = "../../DashboardAssets/imgs/avatar.png";

    if (Model.ImageFile != null)

    {

        string extension = string.Empty;

        extension = Path.GetExtension(Model.ImageExtension);

        byte[] byteData = Model.ImageBytes;

        //Convert byte arry to base64string

        string imreBase64Data = Convert.ToBase64String(byteData);

        imgDataURL = string.Format("data:image/" + extension + ";base64,{0}", imreBase64Data);

    }

}

<img src="@imgDataURL" id="previewimage9" class="rounded-circle" style="height:150px;width:150px; margin-bottom: 15px; cursor: pointer;" />
<input id="image2" name="file2" type="file" class="fileUpload" onchange="readURL(this);" style="width: 90px;" />

<script>

function readURL(input) {

        var ext = $('#image2').val().split('.').pop().toLowerCase();

        if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {

            bootbox.alert("Invalid Image format, Image format must be JPG, JPEG, PNG or GIF.");

            return;

        }

        var picsize = (input.files[0].size);

        if (picsize > 1000000) {

            bootbox.alert("Maximum file size limit is 1MB.");

            return;

        }

        if (input.files && input.files[0]) {

            var reader = new FileReader();

            reader.onload = function (e) {

                $('#previewimage9')

                    .attr('src', e.target.result)

                    .width(150)

                    .height(150);

            };

            reader.readAsDataURL(input.files[0]);           

            $.blockUI();

            var historyId = $("#hdHistoryId").val();

            var formData = new FormData();

            var totalFiles = document.getElementById("image2").files.length;

            for (var i = 0; i < totalFiles; i++) {

                var file = document.getElementById("image2").files[i];

                formData.append("myImage", file);

            }

            $.ajax({

                type: "POST",

                url: '/Winner/UploadImage?historyId=' + historyId,

                data: formData,

                dataType: 'json',

                contentType: false,

                processData: false,

                success: function (response) {

                    alert('succes!!');

                },

                error: function (error) {

                    $.unblockUI();

                    bootbox.alert("Image has been uploaded successfully.");

                }

            });

        }

    }

</script>

 

Step-3) In MVC Controller

public ActionResult UploadImage(string historyId)

{

             EFModel _db = new EFModel ();

             byte[] fileData = null;

            string fileName = string.Empty;

            using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))

            {

                fileName = Request.Files[0].FileName;

                fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);

            }

            var ad = _db.LuckyDrawHistories.Find(historyId);

            ad.ImageBytes = data;

            ad.ImageName = fileName;

            _db.Configuration.ValidateOnSaveEnabled = false;

            _db.SaveChanges();

            var msg = "Success||";

            msg = msg + "/Winner/Index/";

            return Content(msg);

        }

 

 

 

 

 

 

Share This with your friend by choosing any social account


Upcoming Articles
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM
03
07

New Messages

George Floyd
  • Edit Post Edit This Post within a Hour
  • Hide Chat Hide This Post
  • Delete Chat If inappropriate Post By Mistake
  • Report Inappropriate Chat
  • 4.5kb
  • Hi James! Please remember to buy the food for tomorrow! I’m gonna be handling the gifts and Jake’s gonna get the drinks
  • Hi James! Please remember to buy the food for tomorrow! I’m gonna be handling the gifts and Jake’s gonna get the drinks
  • Hi James! Please remember to buy the food for tomorrow! I’m gonna be handling the gifts and Jake’s gonna get the drinks