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

Last Reply 16 days ago By dharmendr

Posted 20 days ago

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).

Posted 16 days ago

Hi MehmetBil,

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

SQL

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

HTML

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnSave" Text="Save" runat="server" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></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;
                        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;
            $.ajax({
                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) {
                    alert(r.responseText);
                },
                failure: function (r) {
                    alert(r.responseText);
                }
            });
            return false;
        });
    });
</script>

ImageService

C#

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 = "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 ImageService : System.Web.Services.WebService
{

    public ImageService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    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);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
        }
    }

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

}

VB.Net

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.
<System.Web.Script.Services.ScriptService()>
<WebService(Namespace:="http://tempuri.org/")>
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Public Class ImageService
    Inherits System.Web.Services.WebService

    <WebMethod>
    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)
                    conn.Open()
                    cmd.ExecuteNonQuery()
                    conn.Close()
                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