Save binary image in Database using ASMX WebService and jQuery Ajax in ASP.Net

Last Reply on Sep 26, 2017 05:55 AM By AnandM

Posted on Sep 20, 2017 11:23 PM

Store Image in sql server db using asp.net webservices

 

You are viewing reply posted by: AnandM on Sep 26, 2017 05:55 AM.
Posted on Sep 26, 2017 05:55 AM

Hi akshay806,

I have created a sample which full fill your requirement you need to modify the code according to your need.

I have taken reference from below articles and links to achieve the task.

  1. Select Insert Edit Update and Delete in GridView using Entity Framework in ASP.Net
  2. Call (Consume) Web Service (ASMX) using jQuery AJAX in ASP.Net
  3. Save binary data in Database and retrieve and display in image control using jQuery Ajax in ASP.Net

Refer below sample code and modify it according to your need.

SQL

CREATE TABLE [dbo].[tblFiles](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NULL,
	[ContentType] [varchar](50) NULL,
	[Data] [varbinary](max) NULL,
 CONSTRAINT [PK_tblFiles] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Web Service(ASMX)

ImageSaveWebServic.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ImagesModel;
/// <summary>
/// Summary description for ImageSaveWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class ImageSaveWebService : System.Web.Services.WebService
{
    [WebMethod]
    public string SaveImage(FileData data)
    {
        using (ImagesEntities imageFile = new ImagesEntities())
        {
            tblFile imageData = new tblFile
            {
                Name = data.Name,
                ContentType = data.ContentType,
                Data = Convert.FromBase64String(data.Data)
            };
            imageFile.AddTotblFiles(imageData);
            imageFile.SaveChanges();
            return "Data Saved Successfully";
        }
    }

    public class FileData
    {
        public string Data { get; set; }

        public string ContentType { get; set; }

        public string Name { get; set; }
    }
}

HTML

<div>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                <asp:FileUpload ID="FileUpload1" runat="server" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSave" Text="Save" runat="server" CssClass="btn btn-primary" />
            </td>
        </tr>
    </table>
</div>
<div>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript">
        $(function () {
            var reader = new FileReader();
            var fileName;
            var contentType;
            $('[id*=FileUpload1]').change(function () {
                if (typeof (FileReader) != "undefined") {
                    var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                    $($(this)[0].files).each(function () {
                        var file = $(this);
                        if (regex.test(file[0].name.toLowerCase())) {
                            fileName = file[0].name;
                            contentType = file[0].type;
                            reader.readAsDataURL(file[0]);
                        } else {
                            alert(file[0].name + " is not a valid image file.");
                            return false;
                        }
                    });
                } else {
                    alert("This browser does not support HTML5 FileReader.");
                }
            });

            $("[id*=btnSave]").click(function () {
                var byteData = reader.result;
                byteData = byteData.split(';')[1].replace("base64,", "");
                var obj = {};
                obj.Data = byteData;
                obj.Name = fileName;
                obj.ContentType = contentType;
                $.ajax({
                    type: "POST",
                    url: "ImageSaveWebService.asmx/SaveImage",
                    data: '{data : ' + JSON.stringify(obj) + ' }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        alert(r.d);
                    },
                    error: function (r) {
                        alert(r.responseText);
                    },
                    failure: function (r) {
                        alert(r.responseText);
                    }
                });
                return false;
            });
        });
    </script>
</div>

ScreenShot