how to upload files in asp.net core using web API

Updated : May 27, 2020 in Asp.net core

how to upload files in asp.net core using web API

in this article, we will learn about how to upload files in asp.net core using web API step by step using console application.

In the previous article we will learn how to upload files in asp.net core without using web Apis there we are discussed single file, mutable files uploading, here we will learn the same concept using WebApi.

  • Create Asp.net Core WebAPI project
  • Implement  configuration section
  • Add Image folder
  • Add Business model Class
  • Add controller
  • Implement the web API class

Create ASP.NET Core Web API Project

Go to visual studio On the Visual Studio, create a new ASP.NET Core Web Application project

create Asp.net core project

Select API Template and Click Ok button to Finish

create Asp.net core project

Implement configuration section:            

Open Startup.cs file in your Project and add new configurations code given below as below:

namespace FilesUploadUsing_AspCorewebapi
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

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

            app.UseStaticFiles();

            app.UseMvc();
        }
    }
}

Add image folder: Create a new folder named images in wwwroot folder. all static files are  we will be stored in wwwroot folder in asp.net core for more detail about how to access the Static files  in asp.net core in details 

Add Business model Class:

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

namespace FilesUploadUsing_AspCorewebapi.Models
{
    public class FileUpload
    {
        public long Length { get; set; }
        public string Name { get; set; }
    }
}

Add controller:Create a new folder named Controllers in your project. In this folder, create a new controller named FileManagerController.cs as given below:

namespace FilesUploadUsing_AspCorewebapi.Controllers
{
    public class FileManagerController : Controller
    {
        [HttpPost("upload")]
        public async Task<IActionResult> Upload(List<IFormFile> files)
        {
            try
            {
                var result = new List<FileUpload>();
                foreach (var file in files)
                {
                    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", file.FileName);
                    var stream = new FileStream(path, FileMode.Create);
                    file.CopyToAsync(stream);
                    result.Add(new FileUpload() { Name = file.FileName, Length = file.Length });
                }
                return Ok(result);
            }
            catch
            {
                return BadRequest();
            }
        }
    }
}

Implement the web API class:

Go to model folder add one more entity class named as result.cs

namespace FilesUploadUsing_AspCorewebapi.Models
{
    public class Result
    {
        public long Length { get; set; }
        public string Name { get; set; }
    }
}

Add UploadRestClientModel :in asp.net core UploadRestClientModel class contain methods call Web API. go to nuget package Add reference to System.Net.Http.Formatting library

Add a class named as UploadRestClientModel.cs in your model folder

namespace FilesUploadUsing_AspCorewebapi.Models
{
    public class UploadRestClientModel
    {
        private string BASE_URL = "https://localhost:44381/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;
            }
        }
    }
}

Run Console Application

 public static void Main(string[] args)
        {
            try
            {
                var fileInfos = new List<FileInfo>() {
                    new FileInfo(@"C:\Users\Administrator\Desktop\Articels\img1.jpg"),
                    new FileInfo(@"C:\Users\Administrator\Desktop\Articels\img2.jpg"),
                    new FileInfo(@"C:\Users\Administrator\Desktop\Articels\img3.jpg")
                };
                var uploadRestClientModel = new UploadRestClientModel();
                var result = uploadRestClientModel.Upload(fileInfos).Result;
                var itemsResults = result.Content.ReadAsAsync<List<FileResult>>().Result;
                Console.WriteLine("Status: " + result.StatusCode);
                foreach (var fileResult in itemsResults)
                {
                    Console.WriteLine("File name: " + fileResult.Length);
                   Console.WriteLine("File size: " + fileResult.Name);
                    Console.WriteLine("====================");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
            // CreateWebHostBuilder(args).Build().Run();
        }

Out Put:

Status: OK
File name: img1.jpg
File size: 3095
====================
File name: img2.jpg
File size: 4066
====================
File name: img3.jpg
File size: 5195
====================

Like
Like Love Haha Wow Sad Angry
1

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x