In this article I will explain with an example, how to upload files using AngularJS ngFileUpload in ASP.Net Core MVC.
This article makes use of ngFileUpload AngularJS module for uploading files using AngularJS in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core 7, please refer my article ASP.Net Core 7: Hello World Tutorial with Sample Program example.
 
 

Uploads Folder Location

The file will be saved inside the Uploads Folder (Directory) of wwwroot Folder (Directory).
Upload files using AngularJS ngFileUpload in ASP.Net Core
 
 

Controller

The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

This Action method handles the call made by the AngularJS function in the View.
Note: The following Action method handles AJAX calls and since a String value is returned, the return type is set to ContentResult.
 
First, the path of the Folder (Directory) where uploaded files will be saved is fetched using IWebHostingEnvironment interface.
Note: The IWebHostEnvironment interface is injected using Dependency Injection inside the Controller, for more details please refer Using IWebHostEnvironment in ASP.Net Core.
           For more details on how to access Static Files in Core, please refer my article Static Files (Images, CSS and JS files) in ASP.Net Core.
 
Then, a check is performed whether Folder (Directory) exists, if not then the Folder (Directory) is created.
A FOR EACH loop is executed over the selected files using Request.From.Files collection.
An object of Stream class is created and using CopyTo method of IFormFile class each file is saved in the Uploads Folder (Directory).
Finally, a success response is sent back to the AngularJS client.
C#
public class HomeController : Controller
{
      private IWebHostEnvironment Environment;
      public HomeController(IWebHostEnvironment _environment)
      {
           this.Environment = _environment;
      }
 
      public IActionResult Index()
      {
            return View();
      }
 
      [HttpPost]
      public ContentResult Upload()
      {
            string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
            if (!Directory.Exists(path))
            {
                  Directory.CreateDirectory(path);
            }
 
            foreach (IFormFile file in Request.Form.Files)
            {
                  string filePath = Path.Combine(path, file.FileName);
 
                  using (Stream stream = new FileStream(filePath, FileMode.Create))
                  {
                        file.CopyTo(stream);
                  }
            }
 
            return Content("Success");
      }
}
 
 

View

Inside the View, the following AngularJS script files are inherited.
1. angular.min.js
2. ng-file-upload.min.js
 
The HTML of the View consists of:
DIV – For applying ng-app and ng-controller AngularJS directives.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
FileUpload – For uploading file.
The HTML INPUT FileUpload has been assigned with the following AngularJS directive.
ngf-select – For handling file uploads.
The HTML FileUpload element is assigned with the multiple property which allows user to select multiple file.
The HTML DIV also consists of an UL with LI element which is used to display the selected files name.
The LI element has been assigned with the following AngularJS directive.
ng-repeat – For repeating the element based on the length of the collection.
Note: If you want to learn more about ng-repeat directive, please refer my article AngularJS ng-repeat example: Populate (Bind) HTML Select DropDownList with Options
 
DIV – For displaying Progress Bar.
The HTML DIV has been assigned with the following AngularJS directive.
ng-show – For showing the elements.
Note: If you want to learn more about ng-show directive, please refer my article Simple AngularJS ng-show and ng-hide Tutorial with example
 
When files are selected in the HTML FileUpload element, it makes call to the UploadFiles function inside the AngularJS Controller.
Inside the UploadFiles function, the selected files are sent to the Controller’s Action method using the Upload function of the ngFileUpload AngularJS module.
Finally, the 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>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.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: '/Home/Upload/',
                        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>
 
 

Permitting uploading Large files in ASP.Net Core

For allowing large file in ASP.Net Core, please refer my article Set MaxRequestLength in ASP.Net Core.
 
 

Screenshot

Upload files using AngularJS ngFileUpload in ASP.Net Core
 
 

Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.
Microsoft Edge  FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Downloads