In this article I will explain with an example, how to upload files using FormData with Progress Bar using Web API in ASP.Net MVC Razor.
This article will illustrate how to upload and send files to Web API AngularJS $http service and HTML5 FormData in ASP.Net MVC Razor.
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;
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.
Then give it a suitable name and click Add.
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 the File is read from the Request.Files collection and saved in the Folder (Directory) created earlier.
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
The View consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML FileUpload element and a Button. Below the Form there’s an HTML5 Progress element for displaying the progress of the uploading File.
The Upload Button has been assigned ng-click directive. When the Button is clicked, the UploadFile function of the Controller gets called.
Inside the UploadFile function, the File is read from the HTML FileUpload element and added to an HTML5 FormData JavaScript object and then the File is uploaded using $http service..
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,
transformRequest: angular.identity,
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 + "</b> 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
The above code has been tested in the following browsers only in versions that support HTML5.
* All browser logos displayed above are property of their respective owners.
Downloads