How to upload a file with .NET CORE Web API 3.1 using IFormFile
How to upload a file with .NET CORE Web API 3.1 using IFormFile

In this post, I will show how to upload a file with .NET CORE Web API 3.1 using IFormFile.

Uploading a file is a process of uploading a file from the user's system to a hosted web application server. You may choose to store the file in the web server's local disc or in the database.

With ASP NET CORE, it is easy to upload a file using IFormFile that comes under the namespace "Microsoft.AspNetCore.Http". IFormFile represents a file sent with the HttpRequest.

Upload File using IFormFile in .NET Core

Methods of uploading files have changed since DOT NET CORE was introduced. To upload a single file using .NET CORE Web API, use IFormFile which Represents a file sent with the HttpRequest.

This is how a controller method looks like which accepts a single file as a parameter.

[HttpPost("upload", Name = "upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> UploadFile(
         IFormFile file,
         CancellationToken cancellationToken)
        {
            if (CheckIfExcelFile(file))
            {
                await WriteFile(file);
            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }

            return Ok();
        }

Code Explanation

The controller action method "UploadFile" accepts file using IFormFile as a parameter. We check whether the file sent is in the required format using a custom private method named "CheckIfExcelFile" which checks whether an incoming file is an excel file. You may change this based on your needs.

       
 private bool CheckIfExcelFile(IFormFile file)
        {
            var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            return (extension == ".xlsx" || extension == ".xls"); // Change the extension based on your need
        }

Once the validation is a success, we save the file to the disc using "WriteFile(file)" method.

private async Task<bool> WriteFile(IFormFile file)
        {
            bool isSaveSuccess = false;
            string fileName;
            try
            {
                var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.

                var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");

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

                var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files",
                   fileName);

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

                isSaveSuccess = true;
            }
            catch (Exception e)
            {
               //log error
            }

            return isSaveSuccess;
        }

Yes, to upload a file with .NET CORE Web API 3.1 using IFormFile is very easy with DOTNET CORE Web API.

How to upload a file with .NET CORE Web API 3.1 using IFormFile

Here is the short video tutorial.

Upload file from Angular, Video demo

Complete Code

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace KarthikTechBlog.API.Controllers
{
    [HttpPost("upload", Name = "upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> UploadFile(
         IFormFile file,
         CancellationToken cancellationToken)
        {
            if (CheckIfExcelFile(file))
            {
                await WriteFile(file);
            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }

            return Ok();
        }

        /// 
        /// Method to check if file is excel file
        /// 
        /// 
        /// 
        private bool CheckIfExcelFile(IFormFile file)
        {
            var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            return (extension == ".xlsx" || extension == ".xls"); // Change the extension based on your need
        }

        private async Task<bool> WriteFile(IFormFile file)
        {
            bool isSaveSuccess = false;
            string fileName;
            try
            {
                var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.

                var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");

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

                var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files",
                   fileName);

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

                isSaveSuccess = true;
            }
            catch (Exception e)
            {
               //log error
            }

            return isSaveSuccess;
        }
    }
}

GitHub Code

You can get the complete code from github https://github.com/karthiktechblog/UploadFileUsingDotNETCore

Reference

Read more about IFormFile Interface
To upload multiple files, use IFormFileCollection Interface

Related Posts

Conclusion

In this post, I showed how to upload a file with .NET CORE Web API 3.1 using IFormFile. 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