ASP.NET Core: How to Upload files in ASP.NET Core Web API using C#

This post shows you How to create a Web API in ASP.NET Core allows you to upload files to Web Server in C#.

To create a Web API upload file in ASP.NET Core. First, You need to know how to create an ASP.NET Core project in Visual Studio. You can view this post: Getting Started with ASP.NET Core 3.0

After finishing creating an ASP.NET Core project, you can create a Web API by right-clicking on Controller folder, then select Add => Controller...

create controller in asp.net coreSelect API Controller - Empty => Add

add empty api controller

Enter your controller name, then click Add button.

 [Route("api/[controller]/[action]")]
 [ApiController]

Modifying your Web API Route as shown above. If you want to call your web api you should enter https://localhost:port/api/file/upload in the web browser.

Next, You need to declare a _webHostEnvirnoment variable that allows you to get the root path, then assign the variable to it in the constructor of your controller.

private readonly IWebHostEnvironment _webHostEnvironment;
public FileController(IWebHostEnvironment webHostEnvironment)
{
    this._webHostEnvironment = webHostEnvironment;
}

Finally, Create an upload method allows you to upload a file to web server via web api controller.

[HttpPost]
public async Task<IActionResult> Upload([FromForm]IFormFile file)
{
    var path = $"{this._webHostEnvironment.WebRootPath}\\files";
    if (!Directory.Exists(path))
        Directory.CreateDirectory(path);
    FileInfo fileInfo = new FileInfo(file.FileName);
    var fullPath = Path.Combine(path, fileInfo.Name);
    if (!System.IO.File.Exists(fullPath))
    {
        using (FileStream fileStream = new FileStream(fullPath, FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }
        return new JsonResult(new { FileName = fileInfo.Name });
    }
    return BadRequest();
}

You can modify the file name to ensure it does not dublicate file name on the web server. Finally, You need to return the file name or anything else when uploading the file successfully.