File Uploading in .NET Web API

Introduction:

In this blog, we are going see about uploading files from .Net Web API. We will cover the necessary code snippets and explain the key concepts involved in the process.

Create a model for file upload

IFormFile” interface is used to handle the file uploads from client side through API. It allows you to read the file content and perform operations such as saving it to disk, processing it, or storing it in a database.

namespace FileUploadInWebApi.Models
{
    public class FileUpload
    {
        public string FileName { get; set; }
        public IFormFile FormFile { get; set; }
    }
}

Here we are creating request model for getting input as a file from the user.

using FileUploadInWebApi.Models;
using Microsoft.AspNetCore.Mvc;

namespace FileUploadInWebApi.Controllers
{
    [ApiController]
    [Route("api")]
    public class FileUploadController : Controller
    {
        [HttpPost("fileUpload")]
        public IActionResult UploadFile([FromForm] FileUpload fileUpload)
        {
            try
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), fileUpload.FileName);

                using(Stream stream = new FileStream(path, FileMode.Create))
                {
                    fileUpload.FormFile.CopyTo(stream);
                }
                return Ok(fileUpload);
            }
            catch(Exception ex)
            {
                throw;
            }
        }
    }
}

Within the UploadFile action, the FileUpload model is received as a parameter. The [FromForm] attribute is applied to indicate that the model is bound from the form data in the request.

The code then proceeds to handle the file upload. It creates a path by combining the current directory with the FileName property from the FileUpload model. This will determine where the uploaded file will be saved on the server.

Using a Filestream, the code opens a stream to the specified path with the FileMode.Create option. It will copy the file data from the FormFile property of the FileUpload model to the stream using the CopyTo method.

Finally, the action returns an Ok result along with the fileUpload model, indicating a successful file upload.

Here I’m inserting an image and FileName. Then the response as follows

Conclusion:

Uploading files in a .NET Web API is an essential skill for developers building web applications that involve file handling. In this blog post, we explored the step-by-step process of uploading files in a .NET Web API.

Related Blogs

Elevate ASP.NET Core Web API speed with caching. Explore in-memory, distributed, and