In this article I will explain with an example, how return multiple Images from Server using Web API in ASP.Net MVC Razor.
The Web API will be called using jQuery AJAX and the Web API will read the Image files from a Folder (Directory) on the Server’s Disk and will return the List of Image files to the calling jQuery AJAX function.
Finally, the returned Image files will be displayed on page using jQuery in ASP.Net MVC Razor.
Note: For beginners in Web API, please refer my article Step by Step Web API Tutorial for Beginners in ASP.Net MVC.
 
 
Model
The Model class consists of the following properties.
public class ImageModel
{
    public string Name { get; set; }
    public string Data { get; set; }
}
 
 

Web API Controller
In order to add a Web API Controller, you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Web API: Return multiple Images in ASP.Net MVC
 
Then give it a suitable name and click Add.
Web API: Return multiple Images in ASP.Net MVC
 
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
 
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
 
The next step is to code the Web API Controller.
 
Namespaces
You will need to import the following namespaces inside the Web API Controller.
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
 
The Web API Controller consists of the following Action method.
 
Action method for getting List of Image Files
Inside this Action method, the list of Image Files are fetched from the Folder (Directory) and then a loop is executed over the list of fetched Images.
Inside the loop, each Image file is read as Byte Array (Binary data) and then an object of ImageModel class is created and the Byte Array is copied to it as Base64 string.
Finally, the Generic List collection of ImageModel class objects is returned to Client using HttpResponseMessage object.
public class ImageAPIController : ApiController
{
    [HttpPost]
    [Route("api/ImageAPI/GetImages")]
    public HttpResponseMessage GetImages()
    {
        List<ImageModel> images = new List<ImageModel>();
 
        //Set the Image Folder Path.
        string path = HttpContext.Current.Server.MapPath("~/Images/");
 
        //Fetch the Image Files.
        foreach (string file in Directory.GetFiles(path))
        {
            //Read the Image as Byte Array.
            byte[] bytes = File.ReadAllBytes(file);
 
            //Convert and add Image as Base64 string.
            images.Add(new ImageModel
            {
                Name = Path.GetFileName(file),
                Data = Convert.ToBase64String(bytes, 0, bytes.Length)
            });
        }
 
        return Request.CreateResponse(HttpStatusCode.OK, images);
    }
}
 
 
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}
 
 
View
The View consists of an HTML Table which will be used to display the Images returned by the Web API.
Inside the jQuery document ready event handler, the GetImages Action method of the Web API is called and a loop is executed over the received Image Files.
Inside the loop, the Name and the actual Image File in Base64 string format is displayed using HTML Table.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <table id="tblImages" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:120px">Image Name</th>
            <th style="width:80px">Image</th>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
            GetImages();
        });
        function GetImages() {
            $.ajax({
                type: "POST",
                url: "/api/ImageAPI/GetImages",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (files) {
                    $.each(files, function () {
                        AppendRow(this);
                    });
                },
                failure: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.d);
                }
            });
        };
 
        function AppendRow(image) {
            var row = $("#tblImages tbody tr:last-child");
 
            //Remove if the row is dummy row.
            if (row.find("td:empty").length > 0) {
                row.remove();
            }
 
            row = row.clone();
            $("td", row).eq(0).text(image.Name);
            $("td", row).eq(1).html("");
            var img = $("<img />");
            img.attr("src", ' data:image/jpg;base64,' + image.Data);
            img.attr("style", "height:80px;width:80px");
            $("td", row).eq(1).append(img);
            $("#tblImages tbody").append(row);
        };
    </script>
</body>
</html>
 
 
Screenshot
Web API: Return multiple Images in ASP.Net MVC
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads