How to Upload Single and Multiple .NET Core 6 Web API - Windows ASP.NET Core Hosting 2024 | Review and ComparisonWindows ASP.NET Core Hosting 2024 | Review and Comparison

In this tutorial, we are going to discuss single and multiple file uploads with the help of the IFormFile Interface and others which are provided by .NET and step-by-step implementation using .NET Core 6 Web API.

Prerequisites

  • .NET Core 6 SDK
  • Visual Studio 2022
  • SQL Server
  • Postman

How to Implement

1. Create a new .NET Core Web API

2. Install following NuGet Packages

3. Create this following file entities

FileDetails.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FileUpload.Entities
{
    [Table("FileDetails")]
    public class FileDetails
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public string FileName { get; set; }
        public byte[] FileData { get; set; }
        public FileType FileType { get; set; }
    }
}

FileUploadModel

namespace FileUpload.Entities
{
    public class FileUploadModel
    {
        public IFormFile FileDetails { get; set; }
        public FileType FileType { get; set; }
    }
}

FileType

namespace FileUpload.Entities
{
    public enum FileType
    {
        PDF = 1,
        DOCX = 2
    }
}

4. Check your DbContextClass.cs class

using FileUpload.Entities;
using Microsoft.EntityFrameworkCore;
namespace FileUpload.Data
{
    public class DbContextClass : DbContext
    {
        protected readonly IConfiguration Configuration;
        public DbContextClass(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        }
        public DbSet<FileDetails> FileDetails { get; set; }
    }
}

5. Create IFileService and FileService files

IFileService

using FileUpload.Entities;
namespace FileUpload.Services
{
    public interface IFileService
    {
        public Task PostFileAsync(IFormFile fileData, FileType fileType);
        public Task PostMultiFileAsync(List<FileUploadModel> fileData);
        public Task DownloadFileById(int fileName);
    }
}

FileService

using FileUpload.Data;
using FileUpload.Entities;
using Microsoft.EntityFrameworkCore;
namespace FileUpload.Services
{
    public class FileService : IFileService
    {
        private readonly DbContextClass dbContextClass;
        public FileService(DbContextClass dbContextClass)
        {
            this.dbContextClass = dbContextClass;
        }
        public async Task PostFileAsync(IFormFile fileData, FileType fileType)
        {
            try
            {
                var fileDetails = new FileDetails()
                {
                    ID = 0,
                    FileName = fileData.FileName,
                    FileType = fileType,
                };
                using (var stream = new MemoryStream())
                {
                    fileData.CopyTo(stream);
                    fileDetails.FileData = stream.ToArray();
                }
                var result = dbContextClass.FileDetails.Add(fileDetails);
                await dbContextClass.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task PostMultiFileAsync(List<FileUploadModel> fileData)
        {
            try
            {
                foreach(FileUploadModel file in fileData)
                {
                    var fileDetails = new FileDetails()
                    {
                        ID = 0,
                        FileName = file.FileDetails.FileName,
                        FileType = file.FileType,
                    };
                    using (var stream = new MemoryStream())
                    {
                        file.FileDetails.CopyTo(stream);
                        fileDetails.FileData = stream.ToArray();
                    }
                    var result = dbContextClass.FileDetails.Add(fileDetails);
                }
                await dbContextClass.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task DownloadFileById(int Id)
        {
            try
            {
                var file =  dbContextClass.FileDetails.Where(x => x.ID == Id).FirstOrDefaultAsync();
                var content = new System.IO.MemoryStream(file.Result.FileData);
                var path = Path.Combine(
                   Directory.GetCurrentDirectory(), "FileDownloaded",
                   file.Result.FileName);
                await CopyStream(content, path);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task CopyStream(Stream stream, string downloadPath)
        {
            using (var fileStream = new FileStream(downloadPath, FileMode.Create, FileAccess.Write))
            {
               await stream.CopyToAsync(fileStream);
            }
        }
    }
}

7. Configure a few services in Program Class and inside DI container

using FileUpload.Data;
using FileUpload.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DbContextClass>();
builder.Services.AddScoped<IFileService, FileService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();

8. Create a new database inside SQL server and named it as FileUploadDemo

9. Create FileDetails table using script below

USE [FileUploadDemo]
GO
/****** Object:  Table [dbo].[FileDetails]    Script Date: 10/1/2022 5:51:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FileDetails](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [FileName] [nvarchar](80) NOT NULL,
    [FileData] [varbinary](max) NOT NULL,
    [FileType] [int] NULL,
 CONSTRAINT [PK_FileDetails] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

10. Put database connection inside the appsettings.json file

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=DESKTOP-****;;Initial Catalog=FileUploadDemo;User Id=sa;Password=database;"
  }
}

11. Run the application

12. Upload a single file using Swagger

13. Use Postman to upload multiple files. Here you can see we use array index to send the file and their type and it will be working fine.

14. Download files on local system at a specified path location

15. You can see your downloaded file

Also, in the database, we can see whatever files we already uploaded using the above endpoints

Conclusion

In this article, we discussed the single and multiple file upload using IFormFile and step-by-step implementation of that using .NET Core Web API and also read and save the files from the database to the specified location.

Happy Coding!