A Web API Controller for a Simple File Upload Procedure – C# and Vb.Net

← PrevNext →

If you are looking for a solution on file upload, then you have come to the right place. Here, in this post I have written a simple file upload procedure in Asp.Net Web API. The controller in the API has the code to upload multiple files and I have written it for C# and VB developers.

You can call a Web API controller from any client application, which is capable of making an http POST request either using jQuery Ajax or XMLHttpRequest object.

Create the FileUpload Web API

Start Visual Studio and from the top left choose File -> New Project. In the New Project window, you will find a list of “Installed Templates”. Choose the language you prefer and select Web -> Asp.Net MVC4 Web Application. Name your application as FileUpload. From the Project Template under New ASP.NET MVC 4 Project, select Web API template and press OK.

If you are newbie in Web API, then I would recommend you to check the below link for step by step creation and implementation of your first Web API application.

My First Web API Application

I don’t need a Model for this example. Just the Controller will do. Therefore, let’s create the Controller for our WebAPI.

Open the Solution Explorer window in the project. Find Controllers folder, right click it and choose Add and Controller…. In the Add Controller window, type FileUploadController in the Controller Name box. From the Template dropdown list, choose Empty MVC controller and click the Add button. It will create a .cs file (.vb for Visual Basic).

FileUploadController.cs (For C#)
using System;

using System.Net.http;
using System.Web.http;

using System.IO;

namespace FileUpload
{
    public class FileUploadController : ApiController
    {
        [HttpPost()]
        public string UploadFiles()
        {
            int iUploadedCnt = 0;

            // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
            string sPath = "";
            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/locker/");

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        // SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
            }

            // RETURN A MESSAGE (OPTIONAL).
            if (iUploadedCnt > 0) {
                return iUploadedCnt + " Files Uploaded Successfully";
            }
            else {
                return "Upload Failed";
            }
        }
    }
}

Note: You must first create a folder in the root directory of your project called locker. You will upload your files in this folder. You may later name the folder as you wish.

FileUploadController.vb (For Vb)
Option Explicit On

Imports System.Net.http
Imports System.Web.http

Imports System.IO

Namespace FileUpload
    Public Class FileUploadController
        Inherits ApiController

        <HttpPost()> _
        Public Function UploadFiles() As String

            Dim iUploadedCnt As Integer = 0

            ' DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
            Dim sPath As String = ""
            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/locker/")

            Dim hfc As System.Web.HttpFileCollection = 
                System.Web.HttpContext.Current.Request.Files

            For iCnt As Integer = 0 To hfc.Count - 1        ' CHECK THE FILE COUNT.
                Dim hpf As HttpPostedFile = hfc(iCnt)
                If hpf.ContentLength > 0 Then

                    ' CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                    If Not File.Exists(sPath & Path.GetFileName(hpf.FileName)) Then

                        ' SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath & Path.GetFileName(hpf.FileName))
                        iUploadedCnt = iUploadedCnt + 1
                    End If
                End If
            Next

            If Val(iUploadedCnt) > 0 Then
                Return iUploadedCnt & " Files Uploaded Successfully"
            Else
                Return "Upload Failed"
            End If

        End Function
    End Class
End Namespace

The controller has a public function called UploadFiles(), which is called by the Ajax using a POST request. The function returns a string value, as a confirmation, saying if the loaded or has failed.

Note: I have not made any changes in the WebApiConfig file. However, if you wish you can make changes according to your requirement.

← Previous