:
Layout
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container body-content">
@RenderBody()
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
@RenderSection("scripts", false)
</body>
</html>
UploadFilePage.css
body {
padding: 30px;
}
form {
display: block;
margin: 20px auto;
background: #eee;
border-radius: 10px;
padding: 15px;
}
.progress {
position: relative;
width: 400px;
border: 1px solid #ddd;
padding: 1px;
border-radius: 3px;
}
.bar {
background-color: #B4F5B4;
width: 0%;
height: 20px;
border-radius: 3px;
}
.percent {
position: absolute;
display: inline-block;
top: 3px;
left: 48%;
}
UploadFile
@{
ViewBag.Title = "Upload Demo";
}
<link href="~/Content/UploadFilePage.css" rel="stylesheet" type="text/css" />
<h2>Upload DEMO</h2>
<form action="/api/upload/UploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="UploadedFile" /><br />
<input type="submit" value="Upload File to Server" />
</form>
<div class="progress">
<div class="bar"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
@section scripts {
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function () {
var bar = $('.bar'), percent = $('.percent'), status = $('#status');
$('form').ajaxForm({
beforeSend: function () {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function (response) {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
alert(response);
},
error: function (xhr) {
status.html(xhr.responseText || 'Error - File upload failed.');
},
complete: function (xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
}
API-
, api-controller-action
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace TestCases.MVC.Controllers
{
public class UploadController : ApiController
{
[HttpPost]
public HttpResponseMessage UploadFile()
{
HttpResponseMessage response = null;
if (HttpContext.Current.Request.Files.AllKeys.Any()) {
HttpContext.Current.Response.ContentType = "text/HTML";
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null) {
var uploadFilesDir = HttpContext.Current.Server.MapPath("~/UploadedFiles");
if (!Directory.Exists(uploadFilesDir)) {
Directory.CreateDirectory(uploadFilesDir);
}
var fileSavePath = Path.Combine(uploadFilesDir, httpPostedFile.FileName);
httpPostedFile.SaveAs(fileSavePath);
response = new HttpResponseMessage(HttpStatusCode.Created) {
Content = new StringContent("Uploaded Successfully")
};
}
}
return response;
}
}
}