Single File Upload in ASP.NET Core Web API


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

project

Select Empty Template

Click Ok button to Finish




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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreWebAPIWithRealApps
{
    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();
        }
    }
}

Create new folder named images in wwwroot folder

Create new folder named Controllers. In this folder, create new controller named FileController.cs, this file contains Web API upload file to server as below:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreWebAPIWithRealApps.Controllers
{
    [Route("api/file")]
    public class FileController : Controller
    {

        [HttpPost("upload")]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            try
            {
                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", file.FileName);
                var stream = new FileStream(path, FileMode.Create);
                file.CopyToAsync(stream);
                return Ok(new { length = file.Length, name = file.FileName });
            }
            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 LearnASPNETCoreWebAPIWithRealApps_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 LearnASPNETCoreWebAPIWithRealApps_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 LearnASPNETCoreWebAPIWithRealApps_Client
{
    public class UploadRestClientModel
    {
        private string BASE_URL = "http://localhost:18942/api/file/";

        public Task<HttpResponseMessage> Upload(FileInfo fileInfo)
        {
            try
            {
                var httpClient = new HttpClient();
                var multipartFormDataContent = new MultipartFormDataContent();
                httpClient.BaseAddress = new Uri(BASE_URL);
                var fileContent = new ByteArrayContent(File.ReadAllBytes(fileInfo.FullName));
                multipartFormDataContent.Add(fileContent, "file", fileInfo.Name);
                return httpClient.PostAsync("upload", multipartFormDataContent);
            }
            catch
            {
                return null;
            }
        }
    }
}
using LearnASPNETCoreWebAPIWithRealApps_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 LearnASPNETCoreWebAPIWithRealApps_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var fileInfo = new FileInfo(@"E:\Photo\thumb2.gif");
                var uploadRestClientModel = new UploadRestClientModel();
                var result = uploadRestClientModel.Upload(fileInfo).Result;
                var fileResult = result.Content.ReadAsAsync<FileResult>().Result;
                Console.WriteLine("Status: " + result.StatusCode);
                Console.WriteLine("File name: " + fileResult.Name);
                Console.WriteLine("File size: " + fileResult.Length);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
    }
}




Status: OK
File name: thumb2.gif
File size: 8063

I recommend you refer to the books below to learn more about the knowledge in this article: