In this article I will explain with an example, how to save (upload) Image files to Server using Web API in ASP.Net MVC Razor.
The Image files will be uploaded to Web API and then inside the Web API, the Image files will be saved in Folder (Directory) on the Server’s Disk 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.
 
 
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.
Web API: Save (Upload) image to Server in ASP.Net MVC
 
Then give it a suitable name and click Add.
Web API: Save (Upload) image to Server 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 two Action methods.
Action method for uploading the Image Files
Inside this Action method, first the Folder (Directory) where the Files will be saved is created if it does not exists.
Then the Name of the Image File is read from Request.Form collection and the Image 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 Image File is returned to the Client which confirms successful upload of the Image File.
 
Action method for getting List of Files
Inside this Action method, the records of Image Files are fetched from the Folder (Directory) and the List is returned to Client using HttpResponseMessage object.
public class ImageAPIController : ApiController
{
    [Route("api/ImageAPI/UploadFiles")]
    [HttpPost]
    public HttpResponseMessage UploadFiles()
    {
        //Create the Directory.
        string path = HttpContext.Current.Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        //Fetch the File.
        HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];
 
        //Fetch the File Name.
        string fileName = Path.GetFileName(postedFile.FileName);
 
        //Save the File.
        postedFile.SaveAs(path + fileName);
 
        //Send OK Response to Client.
        return Request.CreateResponse(HttpStatusCode.OK, fileName);
    }
 
    [HttpPost]
    [Route("api/ImageAPI/GetFiles")]
    public HttpResponseMessage GetFiles()
    {
        string path = HttpContext.Current.Server.MapPath("~/Uploads/");
 
        //Fetch the Image Files.
        List<string> images = new List<string>();
 
        //Extract only the File Names to save data.
        foreach (string file in Directory.GetFiles(path))
        {
            images.Add(Path.GetFileName(file));
        }
 
        return Request.CreateResponse(HttpStatusCode.OK, images);
    }
}
 
 
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 Image File
The Upload Button has been assigned a jQuery Click event handler. When the Button is clicked, the Image File is read from the HTML FileUpload element and added to an HTML5 FormData JavaScript object and then the Image File is uploaded using XmlHttpRequest (XHR).
A Progress event handler is attached to the XmlHttpRequest (XHR), which displays the progress of the Image File being uploaded using the HTML5 Progress element.
Finally, the received Name and uploaded Image File is displayed in the HTML Table.
 
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 Image Files.
Inside the loop, the Name and the actual Image File is displayed in 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" id="file"/>
        <input type="button" id="btnUpload" value="Upload"/>
    </form>
    <progress id="fileProgress" style="display:none"></progress>
    <hr/>
    <table id="tblImages" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:120px">Image Name</th>
            <th style="width:80px">Image</th>
        </tr>
        <tr>
            <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/ImageAPI/GetFiles",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (files) {
                    $.each(files, function () {
                        AppendRow(this);
                    });
                },
                failure: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.d);
                }
            });
        };
 
        function AppendRow(name) {
            var row = $("#tblImages 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).text(name);
            $("td", row).eq(1).html("");
            var img = $("<img />");
            img.attr("src", '@Url.Content("~/Uploads/")' + name);
            img.attr("style", "height:80px;width:80px");
            $("td", row).eq(1).append(img);
            $("#tblImages tbody").append(row);
        };
        $("body").on("click", "#btnUpload", function () {
            var formData = new FormData();
            formData.append("file", $("#file")[0].files[0]);
            $.ajax({
                url: '/api/ImageAPI/UploadFiles',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (fileName) {
                    $("#fileProgress").hide();
                     AppendRow(fileName);
                },
                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 Server in ASP.Net MVC
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads