In this article I will explain with an example, how to upload (insert) and download (retrieve) Files from Folder (Directory) and Path in Database using Web API in ASP.Net MVC Razor.
The Web API will insert the File information into SQL Server database using Entity Framework while the actual File will be saved in Folder (Directory) in ASP.Net MVC Razor.
The Web API will be called using jQuery AJAX and the file will be uploaded to Database using HTML5 Form Data and XmlHttpRequest (XHR).
Database
This article makes use of a table named Files whose schema is defined as follows.
Note: You can download the database table SQL by clicking the download link below.
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;
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 three Action methods.
Action method for inserting File
Inside this Action method, an object of HttpResponseMessage is created and the uploaded File is read from the Request.Files collection.
The uploaded File is first saved in the Folder (Directory) and then its Name and Path is inserted into the Database using Entity Framework.
Then ID and Name of the uploaded file is returned back to the Client using HttpResponseMessage object.
Action method for getting File using ID
Inside this Action method, the FileId is received as parameter. The FileId value is used to reference the record of the inserted File in the Files Entities.
Once the record is referenced, the File data is read from the Folder (Directory) and it is downloaded to the Client as Attachment using the HttpResponseMessage object.
Action method for getting List of Files
Inside this Action method, the records of Files are fetched from the database and the List is returned to Client using HttpResponseMessage object.
public class FileAPIController : ApiController
{
[HttpPost]
[Route("api/FileAPI/SaveFile")]
public HttpResponseMessage SaveFile()
{
//Create HTTP Response.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
//Check if Request contains File.
if (HttpContext.Current.Request.Files.Count == 0)
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//Read the File data from Request.Form collection.
HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];
//Fetch the File Name.
string fileName = Path.GetFileName(postedFile.FileName);
//Set the File Path.
string filePath = @"D:\SavedFiles\" + fileName;
//Save the File in Folder.
postedFile.SaveAs(filePath);
//Insert the File to Database Table.
FilesEntities entities = new FilesEntities();
File file = new File
{
Name = fileName,
Path = filePath
};
entities.Files.Add(file);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, new { id = file.FileId, Name = file.Name });
}
[HttpPost]
[Route("api/FileAPI/GetFiles")]
public HttpResponseMessage GetFiles()
{
FilesEntities entities = new FilesEntities();
var files = from file in entities.Files
select new { id = file.FileId, Name = file.Name };
return Request.CreateResponse(HttpStatusCode.OK, files);
}
[HttpGet]
[Route("api/FileAPI/GetFile")]
public HttpResponseMessage GetFile(int fileId)
{
//Create HTTP Response.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
//Fetch the File data from Database.
FilesEntities entities = new FilesEntities();
File file = entities.Files.ToList().Find(p => p.FileId == fileId);
//Read the File as Byte Array from Folder.
byte[] fileData = System.IO.File.ReadAllBytes(@"D:\SavedFiles\" + file.Name);
//Set the Response Content.
response.Content = new ByteArrayContent(fileData);
//Set the Response Content Length.
response.Content.Headers.ContentLength = fileData.LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = file.Name;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
}
}
View
The View consists of a Form with an HTML FileUpload element and a Button. Below the Form there’s an HTML5 Progress element for displaying the progress of the uploading File.
There’s also an HTML Table which will be used to display the List of uploaded files.
Uploading File
When the Upload button is clicked, an AJAX call is made to the Web API’s Action method SaveFile using jQuery.
The data of the selected File is read using HTML5 FormData and the File is uploaded to the Database using XmlHttpRequest (XHR).
A Progress event handler is attached to the XmlHttpRequest (XHR), which displays the progress of the File being uploaded using the HTML5 Progress element.
Finally, the received ID and Name of the File is displayed in the HTML Table.
Getting File using ID
When the Download link is clicked, the Web API Action method GetFile is called and the ID of the File is passed as parameter.
The File is downloaded as Attachment in browser.
Getting List of Files
Inside the jQuery document ready event handler, the Web API Action method GetFiles is called and a loop is executed over the received File records.
Inside the loop, the ID and Name values of each record is fetched and a row is added to the HTML Table.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<form enctype="multipart/form-data">
<input type="file" name="postedFile"/>
<input type="button" id="btnUpload" value="Upload"/>
</form>
<progress id="fileProgress" style="display:none"></progress>
<hr/>
<table id="tblFiles" cellpadding="0" cellspacing="0">
<tr>
<th style="width:50px">File ID</th>
<th style="width:120px">File Name</th>
<th style="width:80px">Download</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
GetFiles();
});
function GetFiles() {
$.ajax({
type: "POST",
url: "/api/FileAPI/GetFiles",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (files) {
$.each(files, function () {
AppendRow(this.id, this.Name);
});
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
};
function AppendRow(id, name) {
var row = $("#tblFiles tbody tr:last-child");
//Remove if the row is dummy row.
if (row.find("td:empty").length > 0) {
row.remove();
}
row = row.clone();
$("td", row).eq(0).html(id);
$("td", row).eq(1).html(name);
$("td", row).eq(2).html("");
var a = $("<a />");
a[0].href = '@Url.Content("~/api/FileAPI/GetFile?FileId=")' + id;
a.html("Download");
$("td", row).eq(2).append(a);
$("#tblFiles tbody").append(row);
};
$("body").on("click", "#btnUpload", function () {
$.ajax({
url: '@Url.Content("~/api/FileAPI/SaveFile")',
type: 'POST',
data: new FormData($('form')[0]),
cache: false,
contentType: false,
processData: false,
success: function (response) {
$("#fileProgress").hide();
AppendRow(response.id, response.Name);
},
xhr: function() {
var fileXhr = $.ajaxSettings.xhr();
if (fileXhr.upload) {
$("progress").show();
fileXhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
$("#fileProgress").attr({
value: e.loaded,
max: e.total
});
}
}, false);
}
return fileXhr;
}
});
});
</script>
</body>
</html>
Screenshot
Downloads