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

on Sep 06, 2018 06:33 AM

i want to use webservices (.net) jquery(ajax) .. my senario is adding an image to a server and save its name , adress and guid to a mssql database

i want to save images to a folder in server side by using jquery and then i ll save its path in a database.. (by webservices and jquery).

Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Sep 10, 2018 03:56 AM

Hi MehmetBil,

Refer below example and correct your code as per your requirement.


CREATE TABLE [dbo].[tblFiles_Path]
    [Id] [varchar](50) NOT NULL,
    [Name] [varchar](50) NULL,
    [Path] [varchar](50) NULL


<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnSave" Text="Save" runat="server" />
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    $(function () {
        var reader = new FileReader();
        var fileName;
        $('[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;
                    } 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;
                type: "POST",
                url: "ImageService.asmx/SaveImage",
                data: '{fileData : ' + JSON.stringify(obj) + ' }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {

                error: function (r) {
                failure: function (r) {
            return false;



using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for ImageService
/// </summary>
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
public class ImageService : System.Web.Services.WebService

    public ImageService()

        //Uncomment the following line if using designed components 

    public void SaveImage(FileData fileData)
        if (!string.IsNullOrEmpty(fileData.Name))

            byte[] imageBytes = Convert.FromBase64String(fileData.Data);
            string filePath = "~/Files/" + fileData.Name;
            System.IO.File.WriteAllBytes(Server.MapPath(filePath), imageBytes);

            string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(constr))
                string sql = "INSERT INTO tblFiles_Path VALUES(NEWID(),@Name, @Path)";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                    cmd.Parameters.AddWithValue("@Name", fileData.Name);
                    cmd.Parameters.AddWithValue("@Path", filePath);

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



Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
Public Class ImageService
    Inherits System.Web.Services.WebService

    Public Sub SaveImage(ByVal fileData As FileData)
        If Not String.IsNullOrEmpty(fileData.Name) Then
            Dim imageBytes As Byte() = Convert.FromBase64String(fileData.Data)
            Dim filePath As String = "~/Files/" & fileData.Name
            System.IO.File.WriteAllBytes(Server.MapPath(filePath), imageBytes)
            Dim constr As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
            Using conn As SqlConnection = New SqlConnection(constr)
                Dim sql As String = "INSERT INTO tblFiles_Path VALUES(NEWID(),@Name, @Path)"
                Using cmd As SqlCommand = New SqlCommand(sql, conn)
                    cmd.Parameters.AddWithValue("@Name", fileData.Name)
                    cmd.Parameters.AddWithValue("@Path", filePath)
                End Using
            End Using
        End If
    End Sub

    Public Class FileData
        Public Property Name As String
        Public Property Data As String
    End Class

End Class