Here, we will learn about creating Web API in ASP.NET MVC and will also perform the file upload using Web API. Web API is very important in order to share data from the world.

Prerequisites

  • Basic knowledge of ASP.NET MVC
  • Basic knowledge of Web API
  • Basic knowledge of jQuery

Now, create a new project in ASP.NET Web Application and select the Web API framework when creating the project.

upload-file-using-web-api-in-asp-net-mvc-and-jquery-1

Now it will create a new Web API project in our application.

We will now add the new Web API controller. To create a new controller by right click on the controller folder.

upload-file-using-web-api-in-asp-net-mvc-and-jquery-2

Choose a Web API controller from it and name it as FileUploadApi.

upload-file-using-web-api-in-asp-net-mvc-and-jquery-3

Open the FileUploadApiController and add the code in it.

public class FileUploadApiController : ApiController
   {
       [HttpPost]
       public Task<HttpResponseMessage> Post()
       {
           List<string> savedFilePath = new List<string>();
           if (!Request.Content.IsMimeMultipartContent())
           {
               throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
           }
           string rootPath = HttpContext.Current.Server.MapPath("~/Files");
           if (!Directory.Exists(rootPath))
               Directory.CreateDirectory(rootPath);
           var pathProvider = new MultipartFileStreamProvider(rootPath);
           var newTask = Request.Content.ReadAsMultipartAsync(pathProvider).
               ContinueWith(task =>
               {
                   if (task.IsCanceled || task.IsFaulted)
                   {
                       Request.CreateErrorResponse(HttpStatusCode.InternalServerError, task.Exception);
                   }
                   foreach (MultipartFileData item in pathProvider.FileData)
                   {
                       try
                       {
                           string fileName = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                           string newFileName = Guid.NewGuid() + Path.GetExtension(fileName);
                           File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
                           Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
                           string fileRelativePath = "~/Files/" + newFileName;
                           Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
                           savedFilePath.Add(fileFullPath.ToString());
                       }
                       catch (Exception ex) { }

                   }
                   return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
               });
           return newTask;
       }
   }

Open the Index.cshtml file in the Home folder

@{
    ViewBag.Title = "FileUpload";
}

<style>
    table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }

    td, th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
    }

    tr:nth-child(even) {
        background-color: #dddddd;
    }

    .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
    }

    .button4 {
        border-radius: 9px;
    }
</style>

<fieldset>

    <legend style="font-family:Arial Black;color:blue">Upload And Download Files Here</legend>
    <div>
        <div class="form-group">
            <div id="updateStatus" class="alert" role="alert" style="display:none;"></div>
        </div>
        <div class="col-md-12" style="text-align:center;margin-bottom:10px;">
            <input type="file" id="fileToBeUploaded" class="btn btn-primary" />
        </div>
        <input id="btnUploadFile" class="button button4" type="button" value="Upload" />
    </div>

    @section Scripts{
        <script>
            $(document).ready(function () {
                $('#btnUploadFile').click(function () {
                    if ($('#fileToBeUploaded').val() == '') {
                        alert('Please select file');
                        return;
                    }
                    var formData = new FormData();
                    var file = $('#fileToBeUploaded')[0];
                    formData.append('file', file.files[0]);
                    $.ajax({
                        url: 'http://localhost:63350/api/fileuploadapi',
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (d) {
                            $('#updateStatus').addClass('alert-success').html('<strong>Upload Done!</strong><a href="' + d + '">Download File</a>').show();
                            $('#fileToBeUploaded').val(null);
                        },
                        error: function () {
                            $('#updateStatus').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();
                        }
                    });
                });
            });
        </script>
    }
</fieldset>

Output:

output