In this article I will explain with an example, how to save (upload) Image files to Database using Web API in ASP.Net MVC Razor.
The Web API will insert and retrieve Image files from SQL Server database using Entity Framework in ASP.Net MVC Razor.
Note: For beginners in Web API, please refer my article Step by Step Web API Tutorial for Beginners in ASP.Net MVC.
 
 
Database
This article makes use of a table named tblFiles whose schema is defined as follows.
Web API: Save (Upload) image to Database in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Web API: Save (Upload) image to Database in ASP.Net MVC
 
 
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.
Web API: Save (Upload) image to Database in ASP.Net MVC
 
Then give it a suitable name and click Add.
Web API: Save (Upload) image to Database in ASP.Net MVC
 
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 converted into an Array of Bytes using BinaryReader class and finally is inserted into the database table.
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 tblFiles Entities.
Once the record is referenced, the File data is read 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];
 
        //Convert the File data to Byte Array.
        byte[] bytes;
        using (BinaryReader br = new BinaryReader(postedFile.InputStream))
        {
            bytes = br.ReadBytes(postedFile.ContentLength);
        }
 
        //Insert the File to Database Table.
        FilesEntities entities = new FilesEntities();
        tblFile file = new tblFile
        {
            Name = Path.GetFileName(postedFile.FileName),
            ContentType = postedFile.ContentType,
            Data = bytes
        };
        entities.tblFiles.Add(file);
        entities.SaveChanges();
 
        return Request.CreateResponse(HttpStatusCode.OK, new { id = file.id, Name = file.Name });
    }
 
    [HttpPost]
    [Route("api/FileAPI/GetFiles")]
    public HttpResponseMessage GetFiles()
    {
        FilesEntities entities = new FilesEntities();
        var files = from file in entities.tblFiles
                    select new { id = file.id, 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();
        tblFile file = entities.tblFiles.ToList().Find(p => p.id == fileId);
 
        //Set the Response Content.
        response.Content = new ByteArrayContent(file.Data);
 
        //Set the Response Content Length.
        response.Content.Headers.ContentLength = file.Data.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(file.ContentType);
        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
Web API: Save (Upload) image to Database in ASP.Net MVC
 
 
Downloads