How to upload a file in ASP.NET Web API
How to upload a file in ASP.NET Web API

In this short post, I will show how to upload a file in ASP.NET Web API. In this example, I will be using FormData to upload a file from any UI technology like JavaScript, Angular and much more.

Using FormData

FormData provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method.

The form uses "multipart/form-data" as encoding type and FormData does the same.

Let's jump into the coding part to see how to upload a file in ASP.NET Web API.

Upload Example

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace KarthikTechBlog.API.Controllers
{
    public class UploadController : ApiController
    {
        private readonly string uploadPath ="~/App_Data/uploads";
        private readonly List allowedFileExtensions = new List() { "pdf", "xlx", "doc", "docx", "xlxs" };

        [HttpPost]
        [ActionName("UploadFile")]
        public async Task UploadFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            
            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.Contents.FirstOrDefault();

            var fileExtension = file.Headers.ContentDisposition.FileName.Split('.')[1];
            if (!allowedFileExtensions.Any(a => a.Equals(fileExtension)))
            {
                return BadRequest($"File with extension {fileExtension} is not allowed");
            }

            await SaveFileToDisc(file, fileExtension); 
            
            await SaveFileToDatabase(file);

            return Ok();
        }

        private async Task SaveFileToDisc(HttpContent file, string extension)
        {
            var fileName = $"{DateTime.Now.Ticks}.{extension}"; 

            var root = System.Web.HttpContext.Current.Server.MapPath(uploadPath);

            var pathBuilt = Path.Combine(root, string.Concat(DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString(), DateTime.Now.Year.ToString()));

            if (!Directory.Exists(pathBuilt))
            {
                Directory.CreateDirectory(pathBuilt);
            }

            var path = Path.Combine(pathBuilt, fileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }

        private async Task SaveFileToDatabase(HttpContent file)
        {
            var byteArray = await file.ReadAsByteArrayAsync();
            var base64String = Convert.ToBase64String(byteArray); // Save this base64 string to database
        }

    }
}

With upload functionality, you can save the incoming file to a disc or save the file to a database after encoding the file to standard Base64 string. You may also perform both operations like saving the file to disc and to the database.

Are you looking for similar upload functionality in ASP NET CORE 3.1? Read this post for more details.

Reference

to read more about MultipartMemoryStreamProvider, visit MultipartStreamProvider Class in MSDN

Related Posts

Conclusion

In this post, I showed how to upload a file in ASP.NET Web API. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

Leave a Reply

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

Verified by MonsterInsights