In this article I will explain with an example, how to upload files using AngularJS and Web API in ASP.Net MVC Razor.
This article will illustrate how to upload multiple files with the standard FileUpload element using HTML5, AngularJS and Web API 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.
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers; 
 
 
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();
    }
}
 
 
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.
Upload files using AngularJS and Web API in ASP.Net MVC
 
Then give it a suitable name and click Add.
Upload files using AngularJS and Web API 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.
The Web API Controller consists of the following Action method.
Action method for uploading the Files
Inside this Action method, first the Folder (Directory) where the Files will be saved is created if it does not exists. 
Then a loop is executed over the Request.Files collection and inside the loop, each File is read from the Request.Files collection and saved in the Folder (Directory) created earlier.
Finally, an OK response is returned to the Client which confirms successful upload of the Files.
public class FileAPIController : ApiController
{
    [Route("api/FileAPI/UploadFiles")]
    [HttpPost]
    public HttpResponseMessage UploadFiles()
    {
        //Create the Directory.
        string path = HttpContext.Current.Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        //Save the Files.
        foreach (string key in HttpContext.Current.Request.Files)
        {
            HttpPostedFile postedFile = HttpContext.Current.Request.Files[key];
            postedFile.SaveAs(path + postedFile.FileName);
        }
 
        //Send OK Response to Client.
        return Request.CreateResponse(HttpStatusCode.OK);
    }
}
 
 
View
The View consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
The HTML DIV consists of an HTML FileUpload element for which the multiple property is set, so that user can select multiple files.
The HTML FileUpload element has also been assigned the ngf-select directive so that when files are selected in the HTML FileUpload element, it makes call to the UploadFiles function inside the AngularJS controller.
The selected files are sent to the Controller’s Action method using the Upload function of the ngFileUpload AngularJS module.
Timeout function has been used which periodically checks the response of the upload and it updates the Progress Bar.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</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%;
        }
    </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, $timeout) {
            $scope.UploadFiles = function (files) {
                $scope.SelectedFiles = files;
                if ($scope.SelectedFiles && $scope.SelectedFiles.length) {
                    Upload.upload({
                        url: "/api/FileAPI/UploadFiles",
                        data: {
                            files: $scope.SelectedFiles
                        }
                    }).then(function (response) {
                        $timeout(function () {
                            $scope.Result = response.data;
                        });
                    }, 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>
    </div>
</body>
</html>
 
 
Uploading Large files
In order to upload large files, you will need to
1. Set the following setting in the system.web section of the Web.Config file. The executionTimeout value is set to 540 seconds while the maxRequestLength is set to the maximum size of the files in Bytes.
<httpRuntime targetFramework="4.5" executionTimeout="540" maxRequestLength="904857600" />
 
2. Set the following setting in the system.webServer section of the Web.Config file. The maxAllowedContentLength is set to the maximum size of the files in Bytes.
<security>
   <requestFiltering>
     <requestLimits maxAllowedContentLength="904857600"></requestLimits>
   </requestFiltering>
</security>
 
 
Screenshot
Upload files using AngularJS and Web API 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