Delete file from server and record from database using WebService in AngularJS

Last Reply one month ago By dharmendr

Posted one month ago

How to delete file from server folder and record from database in AngularJS.

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi rani,

Check this example. Now please take its reference and correct your code.

Database

For this example i have used table named tblFilesPath whose schema and data are defined as follows.

SQL

CREATE TABLE [dbo].[tblFilesPath]
(
    Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    Name NVARCHAR(50) NOT NULL,
    Path NVARCHAR(200) NOT NULL
)
GO
INSERT INTO tblFilesPath VALUES('Chrysanthemum.jpg','Images/Chrysanthemum.jpg')
INSERT INTO tblFilesPath VALUES('Desert.jpg','Images/Desert.jpg')

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http) {
            GetAllFiles();
            function GetAllFiles() {
                $http.post("WebService.asmx/BindFiles", { headers: { 'Content-Type': 'application/json'} })
                .then(function (response) {
                    $scope.Files = eval(response.data.d);
                });
            }
            // Delete File.
            $scope.DeleteData = function (Id, Name) {
                $http.post("WebServiceCS.asmx/DeleteFile", { id: Id }, { headers: { 'Content-Type': 'application/json'} })
                .then(function (response) {
                    GetAllFiles();
                });
            }
        });
    </script>
</head>
<body>
    <div ng-app="MyApp" ng-controller="MyController">
        <table class="table table-striped table-bordered table-hover table-condensed">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Photo</th>
                <th>Action</th>
            </tr>
            <tbody ng-repeat="m in Files">
                <tr>
                    <td>{{m.Id}}</td>
                    <td>{{m.Name}}</td>
                    <td><img alt="{{m.Name}}" ng-src="{{m.Path}}" style="height: 100px; width: 100px" /></td>
                    <td><input type="button" value="Delete" ng-click="DeleteData(m.Id)" class="btn btn-danger" /></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

WebService

C#

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

[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 WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string BindFiles()
    {
        return (new JavaScriptSerializer().Serialize(GetFiles()));
    }

    public List<File> GetFiles()
    {
        List<File> files = new List<File>();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblFilesPath"))
            {
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        files.Add(new File
                        {
                            Id = Convert.ToInt32(sdr["Id"]),
                            Name = sdr["Name"].ToString(),
                            Path = sdr["Path"].ToString()
                        });
                    }
                }
                conn.Close();
            }
        }

        return files;
    }

    [WebMethod]
    public bool DeleteFile(int id)
    {
        // Get details of File to be Deleted.
        File file = GetFiles().Where(x => x.Id == id).FirstOrDefault();

        // Delete record from Database.
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand("DELETE FROM tblFilesPath WHERE Id = @Id"))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Id", id);
                con.Open();
                int rowsAffected = cmd.ExecuteNonQuery();
                con.Close();
                if (rowsAffected > 0)
                {
                    // Delete file from Server Path.
                    if (System.IO.File.Exists((Server.MapPath("~/") + file.Path).Replace("/", "\\")))
                    {
                        System.IO.File.Delete(Server.MapPath("~/") + file.Path.Replace("/", "\\"));
                    }
                }
                return rowsAffected > 0;
            }
        }
    }

    public class File
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }
    }
}

VB.Net

Imports System
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Linq
Imports System.Web.Script.Serialization
Imports System.Web.Services

' 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 WebServiceVB
    Inherits System.Web.Services.WebService

    <WebMethod()>
    Public Function BindFiles() As String
        Return (New JavaScriptSerializer().Serialize(GetFiles()))
    End Function

    Public Function GetFiles() As List(Of File)
        Dim files As List(Of File) = New List(Of File)()
        Using conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As SqlCommand = New SqlCommand("SELECT * FROM tblFilesPath")
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        files.Add(New File With {
                            .Id = Convert.ToInt32(sdr("Id")),
                            .Name = sdr("Name").ToString(),
                            .Path = sdr("Path").ToString()
                        })
                    End While
                End Using
                conn.Close()
            End Using
        End Using

        Return files
    End Function

    <WebMethod()>
    Public Function DeleteFile(ByVal id As Integer) As Boolean
        ' Get details of File to be Deleted.
        Dim file As File = GetFiles().Where(Function(x) x.Id = id).FirstOrDefault()
        ' Delete record from Database.
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As SqlConnection = New SqlConnection(conString)
            Using cmd As SqlCommand = New SqlCommand("DELETE FROM tblFilesPath WHERE Id = @Id")
                cmd.Connection = con
                cmd.Parameters.AddWithValue("@Id", id)
                con.Open()
                Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
                con.Close()
                If rowsAffected > 0 Then
                    ' Delete file from Server Path.
                    If System.IO.File.Exists((Server.MapPath("~/") & file.Path).Replace("/", "\")) Then
                        System.IO.File.Delete(Server.MapPath("~/") & file.Path.Replace("/", "\"))
                    End If
                End If

                Return rowsAffected > 0
            End Using
        End Using
    End Function

    Public Class File
        Public Property Id As Integer
        Public Property Name As String
        Public Property Path As String
    End Class
End Class

Screenshot