Upload file on server using ASP.NET WEB API

Introduction :

This article will help you to understand how to Upload file on server using Asp.Net WEB API. If you are looking for a solution to implement such functionality where user can access this feature from any platform whether it is web, desktop or mobile platform. Examples – DropBox, Google Drive, Facebook etc. We can upload files on their server from any devices either from mobile, web or desktop. You have to create WEB API and expose it to user in order to accomplish this task. Basically ASP.NET developers using HTML file input fields and form submission to upload file on server. By default this file upload process is synchronous. But with using Web API in combination with the asynchronous programming features of the .NET framework we can easily upload files on the server in asynchronous manner.

Create a WEB API Project :

You can follow below steps to create WEB API Project in order to create file upload on server.

  • Open Visual Studio 2013/15/17 either it is Community version, professional version or enterprise version.
  • Click on File Menu
  • Click on New and then Click on Project menu.
  • This will open new window – New project, where you can select project type.
  • Expand Installed, Expand Language and select web.
  • Select .Net framework on which you are going to build your WEB API.
  • Select Template. Here I’ve selected ASP.NET Web Application(.Net Framework)
  • Enter Project Name. Here I’ve entered WEBAPI_FileUpload
  • Click on OK button.

Create Required Classes :

Create a “UploadRepo” folder inside Project WEBAPI_FileUpload where we are going to add three required class which will help us to implement functionality that can upload file on server.

1st : FileUploadDetails.cs 

In FileUploadDetailsclass, we are going to use four properties.

  • FilePath – store path of file where it is going to stored on server.
  • FileName – store name of file.
  • FileLength – store exact size of file.
  • FileCreatedTime – store file creation time.

you can add more properties as per your project requirement.

namespace WEBAPI_FileUpload.UploadRepo
{
    public class FileUploadDetails 
    {
        public string FilePath { get; set; }
        public string FileName { get; set; }
        public long FileLength { get; set; }
        public string FileCreatedTime { get; set; }
        
    }
}

2nd : Mime.cs

In Mime class, we are going to inherit it with ActionFilterAttribute and then override OnActionExecuting.

using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WEBAPI_FileUpload.UploadRepo
{
    public class Mime : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(
                    new HttpResponseMessage(
                        HttpStatusCode.UnsupportedMediaType)
                );
            }
        }
    }
}

3rd : MultiFileUploadProvider.cs

using System.Net.Http;
using System.Net.Http.Headers;

namespace WEBAPI_FileUpload.UploadRepo
{
    public class MultiFileUploadProvider : MultipartFormDataStreamProvider
    {
        public MultiFileUploadProvider(string rootPath) : base(rootPath) { }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            if (headers != null && headers.ContentDisposition != null)
            {
                return headers
                    .ContentDisposition
                    .FileName.TrimEnd('"').TrimStart('"');
            }

            return base.GetLocalFileName(headers);
        }
    }
}

Create a Controller

First we create an ApiControllerthat implements an HTTP POST action handling the file upload. Note that the action returns Task as we read the file asynchronously.

Note: We use the new async/await keywords introduced in Visual Studio 11 Beta but you can equally well use Tasks and the Continue With pattern already present in Visual Studio 2010.

Basically with ASP.NET platform, we used HTML file input fields and form submission to accomplish this task. By default this file upload process is synchronous. But in Web API we can accomplish same task by asynchronous programming features of the .NET framework which help us to to easily upload files on the server in asynchronous manner. As you can see there is async function Post to upload files on server.

using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using WEBAPI_FileUpload.UploadRepo;

namespace WEBAPI_FileUpload.Controllers
{

    public class FileUploadController : ApiController
    {
        // asynchronous function 
        [Mime]
        public async Task<FileUploadDetails> Post()
        {
            // file path
            var fileuploadPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");

            // 
            var multiFormDataStreamProvider = new MultiFileUploadProvider(fileuploadPath);

            // Read the MIME multipart asynchronously 
            await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);

            string uploadingFileName = multiFormDataStreamProvider
                .FileData.Select(x => x.LocalFileName).FirstOrDefault();

            // Create response, assigning appropriate values to properties 
            return new FileUploadDetails
            {
                FilePath = uploadingFileName,

                FileName = Path.GetFileName(uploadingFileName),

                FileLength = new FileInfo(uploadingFileName).Length,

                FileCreatedTime = DateTime.Now.ToLongDateString()
            };
        }
    }
}

WebApiConfig :
When we created Web API project using WebAPI template in the Create Web API Project section, it also added WebApiConfig class in the App_Start folder with default route as shown below. You can customize default routing as per your need.

Follow given link to read more about configuring WEB API routing :
Attribute Routing in ASP.NET Web API 2

using System.Web.Http;

namespace WEBAPI_FileUpload
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {     
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
WEB API URL – http://localhost:58730/api/FileUpload

Testing the Solution : Upload File on Server 

Fine! you have already created a WEB API to upload files on server. You can test same application using POSTMAN or Fiddler. Here we are going to use POSTMAN to upload file on server. Here, I’ve not mentioned any specific type of file format, So you can upload almost any kind of file.

To test WEB API follow below steps one by one.

  1. Select action type – POST
  2. Enter WEB API url
  3. Enter Key name under Body and make sure form-data is selected.
  4. Select File
  5. Finally click on send button to invoke service.
  6. You can see output in JSON format. You can change it here or it can be predefined from code.

 

code-adda upload file on server

Note: You must have a folder in the root directory of your project called UploadedFiles. You will upload your files in this folder. You may later name the folder as you wish. This is where the uploaded files will be saved.

The uploaded result will contain the file uploaded local path in the server, file’s name and length in bytes. You can add any other properties you want.

I hope you enjoyed this guide, for relevant content that was cited please refer to the resources below:
Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME

You can download complete source code from here

Download Source Code

Reference :

Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data

ASP.NET Web API file download service with resume support

Share Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *