Upload and Download files from database using AngularJS in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

How to upload files in database with download option on button click in angularjs

Posted one month ago Modified on 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.

CREATE TABLE [dbo].[tblFilesPath]
(
    Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    Name NVARCHAR(50) NOT NULL,
    Path NVARCHAR(200) NOT NULL
)

HTML

<html>
<head>
    <title>Upload Download File AngularJS</title>
    <style type="text/css">
        body { font-family: Arial; font-size: 10pt; }
        .thumb { width: 24px; height: 24px; float: none; position: relative; top: 7px; }
        form .progress { line-height: 15px; }
        .progress { display: inline-block; width: 100px; border: 3px groove #ccc; }
        .progress > div { font-size: smaller; background-color: red; width: 0; }
        table { border: 1px solid #ccc; }
        table th { background-color: #F7F7F7;color: #333;font-weight: bold; }
        table th, table td { padding: 5px;border-color: #ccc; }
    </style>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ['ngFileUpload'])
        app.controller('MyController', function ($scope, Upload, $http, $timeout) {
            PopulateFiles();
            function PopulateFiles() {
                $http.post("Default.aspx/BindFiles", { headers: { 'Content-Type': 'application/json'} })
                .then(function (response) {
                    $scope.Files = eval(response.data.d);
                });
            }
            $scope.Download = function (path) {
                var config = { responseType: 'blob' }
                var httpGet = $http.get(path, config);
                httpGet.then(function (response) {
                    if (navigator.msSaveBlob) {
                        navigator.msSaveBlob(new Blob([response.data], { type: 'octet/stream' }), path.split('/')[1]);
                    } else {
                        var fileDownload = document.createElement("a");
                        fileDownload.href = path;
                        fileDownload.download = path.split('/')[1];
                        document.body.appendChild(fileDownload);
                        fileDownload.click();
                        document.body.removeChild(fileDownload);
                    }
                });
            }
            $scope.UploadFiles = function (files) {
                $scope.SelectedFiles = files;
                if ($scope.SelectedFiles && $scope.SelectedFiles.length) {
                    Upload.upload({
                        url: 'Handler.ashx',
                        data: {
                            files: $scope.SelectedFiles
                        }
                    }).then(function (response) {
                        $timeout(function () {
                            $scope.Result = response.data;
                            PopulateFiles();
                        });
                    }, function (response) {
                        if (response.status > 0) {
                            var errorMsg = response.status + ': ' + response.data;
                            alert(errorMsg);
                        }
                    }, function (evt) {
                        var element = angular.element(document.querySelector('#dvProgress'));
                        $scope.Progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                        element.html('<div style="width: ' + $scope.Progress + '%">' + $scope.Progress + '%</div>');
                    });
                }
            };
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <input type="file" multiple="multiple" ngf-select="UploadFiles($files)" /><hr /> 
        Files: <ul><li ng-repeat="file in SelectedFiles">{{file.name}}</li></ul>
        <div id="dvProgress" class="progress" ng-show="Progress >= 0"></div><hr />
        <table class="table table-striped table-bordered table-hover table-condensed">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Download</th>
            </tr>
            <tbody ng-repeat="m in Files">
                <tr>
                    <td>{{m.Id}}</td>
                    <td>{{m.Name}}</td>
                    <td><input type="submit" value="Download" ng-click="Download(m.Path)" /></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

Handler

C#

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Web;

public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        foreach (string key in context.Request.Files)
        {
            HttpPostedFile postedFile = context.Request.Files[key];
            string folderPath = context.Server.MapPath("~/Uploads/");
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            postedFile.SaveAs(folderPath + postedFile.FileName);

            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "INSERT INTO tblFilesPath VALUES (@Name,@Path)";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Name", postedFile.FileName);
                    cmd.Parameters.AddWithValue("@Path", "Uploads/" + postedFile.FileName);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        context.Response.StatusCode = 200;
        context.Response.ContentType = "text/plain";
        context.Response.Write("Success");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

VB.Net

<%@ WebHandler Language="VB" Class="Handler" %>

Imports System
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web

Public Class Handler : Implements IHttpHandler
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        For Each key As String In context.Request.Files
            Dim postedFile As HttpPostedFile = context.Request.Files(key)
            Dim folderPath As String = context.Server.MapPath("~/Uploads/")
            If Not Directory.Exists(folderPath) Then
                Directory.CreateDirectory(folderPath)
            End If

            postedFile.SaveAs(folderPath & postedFile.FileName)
            Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using con As SqlConnection = New SqlConnection(constr)
                Dim query As String = "INSERT INTO tblFilesPath VALUES (@Name,@Path)"
                Using cmd As SqlCommand = New SqlCommand(query)
                    cmd.Connection = con
                    cmd.Parameters.AddWithValue("@Name", postedFile.FileName)
                    cmd.Parameters.AddWithValue("@Path", "Uploads/" & postedFile.FileName)
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using
            End Using
        Next

        context.Response.StatusCode = 200
        context.Response.ContentType = "text/plain"
        context.Response.Write("Success")
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class

Namespaces

C#

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

VB.Net

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

Code

C#

[WebMethod]
public static string BindFiles()
{
    return (new JavaScriptSerializer().Serialize(GetFiles()));
}

public static 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;
}

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

VB.Net

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

Public Shared 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

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

Screenshot