Retrieve and display Binary Image from database using AngularJS in ASP.Net

Last Reply 8 months ago By dharmendr

Posted 9 months ago

I have converted binary data of the image to the text form. But, I need to convert the text data to an image, can I have a solution for that using angularjs in asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="imagev2.aspx.cs" Inherits="imagev2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="myapp">
    <div ng-controller="MyController">
        <button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
        <br />
        Data from server: {{myData.fromServer}}
    </div>
    <script>
        angular.module("myapp", [])
            .controller("MyController", function ($scope, $http) {
                $scope.myData = {};
                $scope.myData.doClick = function (item, event) {
                    $http.post('imagev2.aspx/GetEmployees', { data: {} })
                      .success(function (data, status, headers, config) {
                          $scope.myData.fromServer = data.d;
                      })
                      .error(function (data, status, headers, config) {
                          $scope.status = status;
                      });
                }
            }).config(function ($httpProvider) {
                $httpProvider.defaults.headers.post = {};
                $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
            });
    </script>
</body>
</html>

 

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

public partial class imagev2 : System.Web.UI.Page
{
    [WebMethod]
    public static string GetEmployees()
    {        
        SqlCommand cmd = new SqlCommand();
        SqlConnection conn = new SqlConnection(@"Data Source=STAGINGSERVER;Initial Catalog=INVOICE;Persist Security Info=True;User ID=sa;Password=tEknomec@1993");
        DataSet ds = new DataSet();

        try
        {
            conn.Open();
            ds = new DataSet();
            cmd = new SqlCommand("GETDATA", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter ad = new SqlDataAdapter(cmd);
            ad.Fill(ds);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
        }
        return JsonConvert.SerializeObject(ds);
    }

}
Posted 9 months ago Modified on 8 months ago

Hi skp,

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

Using the below article i have created the example.

Save and Retrieve Image from SQL Server Database in ASP.Net MVC

HTML

<form id="form1" runat="server">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" />
<script type="text/javascript">
    var app = angular.module('MyApp', []);
    app.controller("MyController", function ($scope, $http, $window) {
        GetImages(0);
        $scope.Search = function () {
            var id = $scope.id;
            GetImages(id);
        }
        function GetImages(id) {
            var data = { imageId: id };
            $http.post("Default.aspx/GetImages",
            JSON.stringify(data),
            {
                headers: { 'Content-Type': 'application/json' }
            }).then(function (response) {
                $scope.Images = JSON.parse(response.data.d);
            }, function error(response) {
                alert(response.responseText);
            });
        }
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <input type="text" ng-model="id" />
    <input type="button" value="Search" ng-click="Search()" class="btn btn-default" />
    <hr />
    <table class="table table-table-responsive">
        <thead>
            <tr>
                <th>Name</th>
                <th>Image</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="image in Images">
                <td>{{ image.Name }}</td>
                <td><img ng-src="{{'data:image/png;base64,'+image.Data}}" /></td>
            </tr>
        </tbody>
    </table>
</div>

Namespaces

C#

using System.Web.Script.Serialization;
using System.Web.Services;

VB.Net

Imports System.Web.Script.Serialization
Imports System.Web.Services

Code

C#

[WebMethod]
public static string GetImages(int imageId)
{
    FilesEntities entities = new FilesEntities();
    List<tblFile> files = new List<tblFile>();
    List<ImageModel> images = new List<ImageModel>();
    if (imageId > 0)
    {
        files = entities.tblFiles.Where(x => x.id == imageId).ToList();
    }
    else
    {
        files = entities.tblFiles.ToList();
    }
    foreach (tblFile file in files)
    {
        images.Add(new ImageModel
        {
            Id = file.id,
            Name = file.Name,
            Data = Convert.ToBase64String(file.Data, 0, file.Data.Length)
        });
    }
    JavaScriptSerializer js = new JavaScriptSerializer();
    return js.Serialize(images);
}

public class ImageModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Data { get; set; }
}

VB.Net

<WebMethod()>
Public Shared Function GetImages(ByVal imageId As Integer) As String
    Dim entities As FilesEntities = New FilesEntities()
    Dim files As List(Of tblFile) = New List(Of tblFile)()
    Dim images As List(Of ImageModel) = New List(Of ImageModel)()
    If imageId > 0 Then
        files = entities.tblFiles.Where(Function(x) x.id = imageId).ToList()
    Else
        files = entities.tblFiles.ToList()
    End If

    For Each file As tblFile In files
        images.Add(New ImageModel With {
            .Id = file.id,
            .Name = file.Name,
            .Data = Convert.ToBase64String(file.Data, 0, file.Data.Length)
        })
    Next

    Dim js As JavaScriptSerializer = New JavaScriptSerializer()
    Return js.Serialize(images)
End Function

Public Class ImageModel
    Public Property Id As Integer
    Public Property Name As String
    Public Property Data As String
End Class

You need to set value of maxJsonLength property through Web.Config configuration using the system.web.extensions section as shown below.

<system.web.extensions>
    <scripting>
        <webServices>
            <jsonSerialization maxJsonLength="819200000" />
        </webServices>
    </scripting>
</system.web.extensions>

Screenshot


Posted 8 months ago

Hi skp,

Refer below code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script type="text/javascript">
        angular.module("myapp", [])
            .controller("MyController", function ($scope, $http) {
                $scope.myData = {};
                $scope.myData.doClick = function (item, event) {
                    $http.post('Default.aspx/GetEmployees', { data: {} })
                      .success(function (data, status, headers, config) {
                          var result = JSON.parse(data.d);
                          $scope.myData.fromServer = result.Table;
                      })
                      .error(function (data, status, headers, config) {
                          $scope.status = status;
                      });
                }
            }).config(function ($httpProvider) {
                $httpProvider.defaults.headers.post = {};
                $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
            });
    </script>
</head>
<body ng-app="myapp">
    <form id="form1" runat="server">
    <div ng-controller="MyController">
        <button type="button" ng-click="myData.doClick(item, $event)">
            Send AJAX Request</button>
        <br />
        <table class="table table-table-responsive">
            <thead>
                <tr>
                    <th>Image</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="image in myData.fromServer">
                    <td><img ng-src="{{'data:image/png;base64,'+image.Data}}" /></td>
                </tr>
            </tbody>
        </table>
    </div>
    </form>
</body>
</html>

Namespaces

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using Newtonsoft.Json;

Code

[WebMethod]
public static string GetEmployees()
{
    SqlCommand cmd = new SqlCommand();
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
    DataSet ds = new DataSet();
    try
    {
        conn.Open();
        ds = new DataSet();
        cmd = new SqlCommand("GETDATA", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        ad.Fill(ds);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        cmd.Dispose();
        conn.Close();
        conn.Dispose();
    }

    return JsonConvert.SerializeObject(ds);
}

Screenshot