This article will illustrate how to upload multiple files with the standard FileUpload element using HTML5,
AngularJS and
Web API in ASP.Net MVC.
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();
}
}
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Net;
using System.Web.Http;
using System.Net.Http;
Web API Controller
The
Web API Controller consists of the following Action method.
Action method for Handling POST operation
Inside this Action method, first the path of the Folder (Directory) is fetched.
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.Files collection and each file is saved in the Folder (Directory) named Uploads using SaveAs method of HttpPostedFile class.
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
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.
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.
DIV – For displaying Progress Bar.
The HTML DIV has been assigned with the following
AngularJS directive.
ng-show - For showing the elements.
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
Web API 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.5.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>
Permitting uploading Large files in the Web.Config file
In order to upload large files, you will need to add the following settings in the Web.Config file as shown below.
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
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads