Image Preview Using MVC, AngularJS and Web API 2

Image Preview

In my previous article I explained AngualrJS with MVC and WCS Rest service. This article explaiins in detail how to create a simple Image Slideshow using MVC and AngularJs and using Web API 2.

You can also view my previous articles related to AngularJs using MVC and the WCF Rest Serice.

Prerequisites

Visual Studio 2015. You can download it from here. (In my example I have used Visual Studio Community 2015 RC.)

This article explains the following in detail:

  1. Select Image details from the database using EF and WEB API.
  2. Upload Image to our root folder using AngularJs and MVC Controller method.
  3. Insert uploaded image details to the database using AngularJs , MVC and the WEB API.
  4. Display animated images by clicking on Preview Image.

The base idea for this article was from my article on Windows Forms Based Image Slideshow Application. You can also have a look at that article.

Code Part

1. Create Database and Table

We will create a ImageDetails table under the database ImageDB. The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2012.

Note: In my project folder I have all the images for a sample display.

  1. -- =============================================                                  
  2. -- Author      : Shanu                                  
  3. -- Create date : 2015-05-15                                    
  4. -- Description : To Create Database,Table and Sample Insert Query                               
  5. -- Latest                                  
  6. -- Modifier    : Shanu                                  
  7. -- Modify date : 2015-05-15                              
  8. -- =============================================  
  9. --Script to create DB,Table and sample Insert data  
  10. USE MASTER  
  11. GO  
  12. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB  
  13. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'ImageDB' )  
  14. DROP DATABASE DynamicProject  
  15. GO  
  16.   
  17. CREATE DATABASE ImageDB  
  18. GO  
  19.   
  20. USE ImageDB  
  21. GO  
  22.   
  23. -- 1) //////////// ItemMasters  
  24.   
  25. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'ImageDetails' )  
  26. DROP TABLE ImageDetails  
  27. GO  
  28.   
  29. CREATE TABLE [dbo].[ImageDetails](  
  30.     [ImageID] INT IDENTITY PRIMARY KEY,  
  31.     [Image_Path] [varchar](100) NOT NULL,     
  32.     [Description] [varchar](200) NOT NULL)  
  33.    
  34.   
  35. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('1.jpg','Afreen')  
  36. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('2.jpg','Purple Tulip')  
  37. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('3.jpg','Afreen')  
  38. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('4.jpg','Tulip')  
  39. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('5.jpg','Tulip')  
  40. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('6.jpg','Flowers')  
  41. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('7.jpg','Flowers')  
  42. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('8.jpg','Flowers')  
  43. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('9.jpg','Flowers')  
  44. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('10.jpg','Flowers')  
  45. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('11.jpg','Afraz&Afreen')  
  46. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('12.jpg','LoveLock')  
  47. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('13.jpg','Rose')  
  48. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('14.jpg','Yellow Rose')  
  49. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('15.jpg','Red rose')  
  50. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('16.jpg','Cherry blossom')  
  51. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('17.jpg','Afreen')  
  52. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('18.jpg','fish Market')  
  53. INSERT INTO [ImageDetails] ([Image_Path],[Description])  VALUES    ('19.jpg','Afraz')  
  54.   
  55.                    
  56. select * from [ImageDetails]  

2. Create our First MVC Web Application in Visual Studio 2015

Now to create our first MVC web application in Visual Studio 2015.

After installing Visual Studio 2015, click Start then select Programs then select Visual Studio 2015. Then click Visual Studio 2015 RC.

select Visual Studio

Click New -> Project - > Select Web -> ASP.NET Web Application. Select your project's location and enter your web application's name.

Web Application
Select MVC and in "Add Folders and Core reference for:" select the Web API (as in the following) and click OK.

Select MVC

Now we have created our MVC application. As a next step we will add our SQL Server database as an Entity Data Model to our application.

Add Database using ADO.NET Entity Data Model

Right-click our project and click Add -> New Item.

New Item

Select Datathen select ADO.NET Entity Data Model then provide the name for our EF and click Add.

Select ADO
Select EF Designer from database and click Next.

EF Designer

Here click New Connection and provide your SQL-Server Server Name and connect to your database.

New Connection

Here we can see I have given my SQL Server name, Id and PWD. After the connection, the database is selected as ImageDB since we have created the database using my SQL Script.

ImageDB

Click Next and select the table to be used and click Finish.

click finish

Here we can see I have selected our table Imagedetails. This table will be used to get and insert all our images.

table

Here we can see now we have created our shanuItemDetailsModel1.

shanuItemDetailsModel1

Once our entity has been created the next step is to add a WEB API to our controller and write a function to get and insert records.

Procedure to add our WEB API Controller

Right-click the Controllers folder then click Add then click Controller.

Add Controller

Since we will create our WEB API Controller, select Controller and Add Empty WEB API 2 Controller. Provide your name to the Web API controller and click OK. Here for my Web API Controller I have given the name as “ImageController”.

ImageController

Since we have created a Web API controller, we can see our controller has inherited ApiController.

created Web API

As we all know, the Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles. Web APIs has the four methods Get/Post/Put and Delete where:

  • Get is to request data. (Select)
  • Post is to create data. (Insert)
  • Put is to update data.
  • Delete is to delete data.

In our example we will use both Get and Post since we need to get all the image names and descriptions from the database and to insert a new Image Name and Image Description into the database.

Get Method

Now as a next step we need to create an object for our entity and write our Get and Post methods.

We will use a get method to get all the details of the ImageDetails table using an entity object and we will return the result as an IEnumerable. We will use this method in our AngularJs and display the result in a MVC page from the AngularJs controller using Ng-Repeat. We can see the details step-by-step as follows.

  1. public class ImageController : ApiController  
  2. {  
  3.     ImageDBEntities objAPI = new ImageDBEntities();  
  4.   
  5.   
  6. /get all Images  
  7.     [HttpGet]  
  8.     public IEnumerable<ImageDetails> Get()  
  9.     {  
  10.         return objAPI.ImageDetails.AsEnumerable();  
  11.         //return objAPI.ImageDetails.AsEnumerable().OrderByDescending(item => item.ImageID );  
  12.   
  13.     }  
  14.   
  15.   
  16. }  
Post Method

Using the post method we will insert the Image details into the database. If HttpResponseMessage is used in the Action result, the Web API will convert the return value into a HTTP response message.
  1. public class ImageController : ApiController  
  2. {  
  3.     ImageDBEntities objAPI = new ImageDBEntities();  
  4.   
  5.     //get all Images  
  6.     [HttpGet]  
  7.     public IEnumerable<ImageDetails> Get()  
  8.     {  
  9.        return objAPI.ImageDetails.AsEnumerable();  
  10.         //return objAPI.ImageDetails.AsEnumerable().OrderByDescending(item => item.ImageID );  
  11.   
  12.     }  
  13.   
  14.     //insert Image  
  15.     public HttpResponseMessage Post(ImageDetails imagedetails)  
  16.     {  
  17.         if (ModelState.IsValid)  
  18.         {  
  19.             objAPI.ImageDetails.Add(imagedetails);  
  20.             objAPI.SaveChanges();  
  21.             HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, imagedetails);  
  22.             response.Headers.Location = new Uri(Url.Link("DefaultApi"new { id = imagedetails.Image_Path}));  
  23.             return response;  
  24.         }  
  25.         else  
  26.         {  
  27.             return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  28.         }  
  29.     }  
  30. }  
Now we have created our Web API Controller Class. The next step is to create our AngularJs Module and Controller. Let us see how to create our AngularJs Controller. In Visual Studio 2015 it's much easier to add our AngularJs Controller. Let us see see step-by-step how to create and write our AngularJs Controller.

Creating AngularJs Controller

First create a folder inside the Script Folder and I have named the folder “MyAngular”.

MyAngular folder

Now add your Angular Controller inside the folder.

Right-click the MyAngular folder and click Add and New Item. Select Web. Select AngularJs Controller and provide a name to the Controller. I have given my AngularJs Controller the name “Controller.js”.

Controller

Once the AngularJs Controller is created, we can see that, by default, the controller will have the code with the default module definition.

module definition

I changed the preceding code like adding a module and a controller as in the following.

If the AngularJs package is missing then add the package to your project.

Right-click your MVC project and click Manage NuGet Packages. Search for AngularJs and click Install.

AngularJs

Now we can see all the AngularJs packages have been installed and we can see all the files in the Scripts folder.

my AngularJs

In my previous articles related to AngularJs I explained the use of AngularJs ng-repeat to display the data from AngularJs and how to receive data from WCF to Angular Services, how to do simple animation in AngularJs and how to upload images using AnngularJS and a MVC Controller. To see more details about each, kindly refer to my previous article, you can find a link of each at the top of this article.

Now in my controller I will change the code with my Module and Controller as in the following.

First we will add all the references to AngularJs and then we will create a module. I have given my module the name “RESTClientModule”. Since we need to use simple Animation we will add the "ngAnimate" to our Module.

In the controller for using the animation I used $timeout and for the file upload I uses the service FileUploadService. First we start with following.

1. Variable declarations

First I declared all the local variables that need to be used and the current date and store the date using and same, like this I have declared all the variables  that need to be used.

$scope.date.

2. Methods

To get the image details from our Web API we will use the $http.get method as in the following:
  1. $http.get('/api/Image/').success(function (data)  
In this we will receive all the data and store the result in:
  1. $scope.Images = data;   
I will use these images in ng-repeat to display the images one by one.
  1. /// <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5.   
  6.   
  7. var app;  
  8.   
  9.   
  10. (function () {  
  11.     app = angular.module("RESTClientModule", ['ngAnimate']);  
  12. })();  
  13.   
  14.   
  15. app.controller("AngularJs_ImageController", function ($scope, $timeout, $rootScope, $window, $http, FileUploadService) {  
  16.     $scope.date = new Date();  
  17.     $scope.MyName = "Shanu";  
  18.     $scope.Imagename = "";  
  19.     $scope.ShowImage = false;  
  20.     $scope.Description = "";  
  21.     $scope.AnimationImageName = "1.jpg";  
  22.     $scope.ImagesALLVal=[];  
  23.     $scope.icountval = 0  
  24.   
  25.   
  26.     //get all image Details  
  27.     $http.get('/api/Image/').success(function (data) {  
  28.         $scope.Images = data;      
  29.         if ($scope.Images.length > 0) {  
  30.             $scope.onShowImage($scope.Images[0].Image_Path);  
  31.         }  
  32.     })  
  33.     .error(function () {  
  34.         $scope.error = "An Error has occured while loading posts!";  
  35.   
  36.     });  
To preview the image click to display the actual image with simple animation. I will call this method in the Image Click event of AngularJs as ng-Click= onShowImage(currentImage).
  1. $scope.onShowImage = function (Image_Path) {  
  2.      $scope.ShowImage = false;  
  3.      $scope.AnimationImageName = Image_Path  
  4.      
  5.      $timeout(function () {  
  6.          $scope.ShowImage = true;  
  7.      }, 400);  
  8.       
  9.  }.  
Here we can see that when the user clicks on an image with simple animation I will display the animated image.

Animated image

To upload an image and to insert an image name and image description to the database in the save Item button click I will call this function.

In this method I will check that a valid image was uploaded and if all is true then I will pass the image to the service FileUploadService. If the upload is a success then I will insert the Image details of ImageName and Image Description into the database by calling the Web API post method and pass the data for insert. $http.post('/api/Image/', ItmDetails).
  1. //Save File  
  2. $scope.SaveFile = function () {  
  3.     $scope.IsFormSubmitted = true;  
  4.   
  5.     $scope.Message = "";  
  6.   
  7.     $scope.ChechFileValid($scope.SelectedFileForUpload);  
  8.   
  9.     if ($scope.IsFormValid && $scope.IsFileValid) {  
  10.   
  11.         FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {  
  12.   
  13.             var ItmDetails = {  
  14.                 Image_Path: $scope.Imagename,  
  15.                 Description: $scope.Description  
  16.             };  
  17.             $http.post('/api/Image/', ItmDetails).success(function (data) {  
  18.                 alert("Added Successfully!!");  
  19.                 $scope.addMode = false;  
  20.                 $scope.Images.push(data);  
  21.                 $scope.loading = false;  
  22.             }).error(function (data) {  
  23.                 $scope.error = "An Error has occured while Adding Customer! " + data;  
  24.                 $scope.loading = false;  
  25.             });  
  26.             alert(d.Message + " Item Saved!");  
  27.             $scope.IsFormSubmitted = false;  
  28.             ClearForm();  
  29.   
  30.         }, function (e) {  
  31.             alert(e);  
  32.         });  
  33.     }  
  34.     else {  
  35.         $scope.Message = "All the fields are required.";  
  36.     }  
  37.   
  38. };  
fac.UploadFile = function (file)

In this method we are using $http.post.
Here I have passed our image file to the MVC Home Controller and our HTTPost method is as in the following:
  1. .factory('FileUploadService', function ($http, $q) {  
  2.   
  3.     var fac = {};  
  4.     fac.UploadFile = function (file) {  
  5.         var formData = new FormData();  
  6.         formData.append("file", file);  
  7.   
  8.         var defer = $q.defer();  
  9.         $http.post("/Home/UploadFile", formData,  
  10.             {  
  11.                 withCredentials: true,  
  12.                 headers: { 'Content-Type': undefined },  
  13.                 transformRequest: angular.identity  
  14.             })  
  15.         .success(function (d) {  
  16.             defer.resolve(d);  
  17.         })  
  18.         .error(function () {  
  19.             defer.reject("File Upload Failed!");  
  20.         });  
  21.   
  22.         return defer.promise;  
  23.   
  24.     }  
Note: For $http.post(“”) we need to provide our MVC Controller name and our HTTPost method name, where we uploaded the image to our root folder. The following is the code that is used to upload an image in our MVC Controller.
  1. [HttpPost]  
  2. public JsonResult UploadFile()  
  3. {  
  4.     string Message, fileName;  
  5.     Message = fileName = string.Empty;  
  6.     bool flag = false;  
  7.     if (Request.Files != null)  
  8.     {  
  9.         var file = Request.Files[0];  
  10.         fileName = file.FileName;  
  11.         try  
  12.         {  
  13.             file.SaveAs(Path.Combine(Server.MapPath("~/Images"), fileName));  
  14.             Message = "File uploaded";  
  15.             flag = true;  
  16.         }  
  17.         catch (Exception)  
  18.         {  
  19.             Message = "File upload failed! Please try again";  
  20.         }  
  21.   
  22.     }  
  23.     return new JsonResult { Data = new { Message = Message, Status = flag } };  
  24. }  
We can see an example to upload an image to our application. Browse and select an image to be uploaded to our root folder.

root folder

Enter the description of the image and click Save Item to upload the image and save the item to the database. Once the image has been saved we can see the success message as in the following.

message

Now we can see our new image has been uploaded to our root folder and inserted into the database. In the image list we can see our new Image.

Image

Supported Browsers: Chrome and Firefox.

Up Next
    Ebook Download
    View all
    Learn
    View all