In this article I will explain with an example, how to upload files using
FormData with Progress Bar using
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.Net.Http;
using System.Web;
using System.Web.Http;
Web API Controller
The
Web API Controller consists of the following Action method.
Action method for handling POST operations
Inside this Action method, first the path of the Folder (Directory) where uploaded file will be saved is get.
Then, a check is performed whether the Folder (Directory) exists, if not then the Folder (Directory) is created.
After that, the selected file is saved in the Folder (Directory) named Uploads using SaveAs method of HttpPostedFileBase class.
Finally, an OK response along with the name of the File is returned to the Client which confirms successful upload of the File.
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 File.
HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
//Send OK Response to Client.
return Request.CreateResponse(HttpStatusCode.OK, fileName);
}
}
View
HTML Markup
Inside the View, the following JS file is inherited.
1. angular.min.js
The HTML of the View consists of:
div – For applying
ng-app and
ng-controller AngularJS directives.
FileUpload – For selecting file.
Button – For uploading selected file.
The HTML INPUT Button has been assigned with the following
AngularJS directive.
ng-click – Trigger when user clicks the Button.
Progress – For displaying Progress Bar.
SPAN – For displaying uploaded File Name.
When the Button is clicked, the UploadFile function is executed.
Inside the UploadFile function, the File is read from the HTML FileUpload element and added to an HTML5 FormData.
The
$http service is used to make an
AJAX call to the
Web API Controller’s Action method.
The $http service has following properties and event handlers.
Properties
1. method – The method type of HTTP Request i.e. GET or POST. Here it is set to POST.
2. url – URL of the
Web API Controller’s Action method.
3. data – The parameters to be sent to the
Web API Controller’s method i.e. HTML5
FormData.
4. headers - List of headers to be specified for the HTTP Request.
5. uploadEventHandlers – It provides event handlers for updating Progress Bar.
Event Handlers
1. success – This event handler is triggered once the
AJAX call is successfully executed.
2. error – This event handler is triggered when the
AJAX call encounters an error.
The name of the uploaded file returned from the
AJAX call is set in the HTML SPAN element inside the
Success event handler.
A Progress event handler is attached to the $http service, which displays the progress of the File being uploaded using the HTML5 Progress element.
Finally, the received Name of the uploaded File is displayed in an HTML SPAN element.
@{
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">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
var fileProgress = document.getElementById("fileProgress");
var message = document.getElementById("lblMessage");
$scope.UploadFile = function () {
fileProgress.style.display = "block";
var formData = new FormData();
formData.append(file, document.getElementById("file").files[0]);
var post = $http({
method: "POST",
url: "/api/FileAPI/UploadFiles",
data: formData,
headers: { 'Content-Type': undefined },
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
fileProgress.setAttribute("value", e.loaded);
fileProgress.setAttribute("max", e.total);
}
}
}
});
post.success(function (data, status) {
message.innerHTML = "<b>" + data + "has been uploaded.";
fileProgress.style.display = "none";
});
post.error(function (data, status) {
$window.alert(data.Message);
});
};
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input id="file" type="file" />
<input type="button" value="Upload" ng-click="UploadFile()" />
<progress id="fileProgress" style="display: none"></progress>
<hr />
<span id="lblMessage" style="color: Green"></span>
</div>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads