Multiple File Upload in ASP.NET Core 3 Web API

On the Visual Studio, create new ASP.NET Core Web Application project

Input Project Name and select Project Location




Select Empty Template and click Create button to Finish

Structure of New Project




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCore3WebAPIWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Create new folder named images in wwwroot folder




Create Models folder. In this folder, create new class named FileUploadResult.cs as below:

FileUploadResult Entity

namespace LearnASPNETCore3WebAPIWithRealApps.Models
{
    public class FileUploadResult
    {
        public long Length { get; set; }

        public string Name { get; set; }
    }
}

Create new folder named Controllers. In this folder, create new controller named FileController.cs as below:

using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using LearnASPNETCore3WebAPIWithRealApps.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCore3WebAPIWithRealApps.Controllers
{
    [Route("api/file")]
    public class FileController : Controller
    {
        private IWebHostEnvironment iwebHostEnvironment;

        public DemoController(IWebHostEnvironment _iwebHostEnvironment)
        {
            this.iwebHostEnvironment = _iwebHostEnvironment;
        }

        [HttpPost("upload")]
        public async Task<IActionResult> Upload(List<IFormFile> files)
        {
            try
            {
                var result = new List<FileUploadResult>();
                foreach (var file in files)
                {
                    var path = Path.Combine(this.iwebHostEnvironment.WebRootPath, "images", file.FileName);
                    var stream = new FileStream(path, FileMode.Create);
                    await file.CopyToAsync(stream);
                    result.Add(new FileUploadResult() { Name = file.FileName, Length = file.Length });
                }
                return Ok(result);
            }
            catch
            {
                return BadRequest();
            }
        }

    }
}




Create Console App (.NET Framework) Project in Visual Studio.

Create Models folder in Console Application. In this folder, create new class named FileResult.cs as below:

FileResult Entity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client
{
    public class FileResult
    {
        public long Length { get; set; }

        public string Name { get; set; }
    }
}




UploadRestClientModel class contain methods call Web API. Add reference to System.Net.Http.Formatting library from Nuget Packages

using LearnASPNETCore3WebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client
{
    public class UploadRestClientModel
    {
        private string BASE_URL = "http://localhost:18942/api/file/";

        public Task<HttpResponseMessage> Upload(List<FileInfo> fileInfos)
        {
            try
            {
                var httpClient = new HttpClient();
                var multipartFormDataContent = new MultipartFormDataContent();
                httpClient.BaseAddress = new Uri(BASE_URL);
                foreach (var fileInfo in fileInfos)
                {
                    var fileContent = new ByteArrayContent(File.ReadAllBytes(fileInfo.FullName));
                    multipartFormDataContent.Add(fileContent, "files", fileInfo.Name);
                }
                return httpClient.PostAsync("upload", multipartFormDataContent);
            }
            catch
            {
                return null;
            }
        }
    }
}




using LearnASPNETCore3WebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var fileInfos = new List<FileInfo>() {
                    new FileInfo(@"E:\Photo\thumb1.gif"),
                    new FileInfo(@"E:\Photo\thumb2.gif"),
                    new FileInfo(@"E:\Photo\thumb3.gif")
                };
                var uploadRestClientModel = new UploadRestClientModel();
                var result = uploadRestClientModel.Upload(fileInfos).Result;
                var fileResults = result.Content.ReadAsAsync<List<FileResult>>().Result;
                Console.WriteLine("Status: " + result.StatusCode);
                foreach (var fileResult in fileResults)
                {
                    Console.WriteLine("File name: " + fileResult.Name);
                    Console.WriteLine("File size: " + fileResult.Length);
                    Console.WriteLine("====================");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
    }
}
Status: OK
File name: thumb1.gif
File size: 5095
====================
File name: thumb2.gif
File size: 8063
====================
File name: thumb3.gif
File size: 8192
====================