DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Designing API-First EMR Architectures in .NET: Enabling Modular Growth in Compliance-Driven Systems
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI
  • Microservices With .NET Core: Building Scalable and Resilient Applications

Trending

  • From printTriangularNumber to Duff’s Device: Mastering Java Switch Statements Old and New
  • The ORM Is Over: AI-Written SQL Is the New Data Access Layer
  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Testing Is Not About Finding Bugs
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Upload Single and Multiple Files Using the .NET Core 6 Web API

Upload Single and Multiple Files Using the .NET Core 6 Web API

We will discuss file uploads with the help of the IFormFile Interface and others provided by .NET and step-by-step implementation using .NET Core 6 Web API.

By 
Jaydeep Patil user avatar
Jaydeep Patil
·
Oct. 07, 22 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

We will discuss single and multiple file uploads with the help of the IFormFile Interface and others provided by .NET and step-by-step implementation using .NET Core 6 Web API.

Agenda

  • Introduction
  • Step-by-step Implementation

Prerequisites

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

Introduction

  • .NET provides an IFormFile interface representing transmitted files in an HTTP request.
  • It also provides many properties like ContentDisposition, ContentType, FileName, Headers, Name, and Length.
  • IFormFile also provides many methods, like copying the request stream content, opening the request stream for reading, and many more.

Step-By-Step Implementation

Step 1

Create a new .NET Core Web API.

Create a new .NET Core Web API.

Step 2

Install the following NuGet packages:

Install the following NuGet packages.

Step 3

Create the following file entities:

FileDetails.cs

C#
 
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

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

FileType 

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

Step 4

Next, the DbContextClass.cs class inside the Data folder.

C#
 
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; }
    }
}

Step 5

It creates IFileService and FileService files.

IFileService

C#
 
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 

C#
 
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);
            }
        }
    }
}

Step 6

Create FilesController.cs inside the controller section.

C#
 
using FileUpload.Entities;
using FileUpload.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FileUpload.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly IFileService _uploadService;
        public FilesController(IFileService uploadService)
        {
            _uploadService = uploadService;
        }
        /// <summary>
        /// Single File Upload
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("PostSingleFile")]
        public async Task<ActionResult> PostSingleFile([FromForm] FileUploadModel fileDetails)
        {
            if(fileDetails == null)
            {
                return BadRequest();
            }
            try
            {
                await _uploadService.PostFileAsync(fileDetails.FileDetails, fileDetails.FileType);
                return Ok();
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Multiple File Upload
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("PostMultipleFile")]
        public async Task<ActionResult> PostMultipleFile([FromForm] List<FileUploadModel> fileDetails)
        {
            if (fileDetails == null)
            {
                return BadRequest();
            }
            try
            {
                await _uploadService.PostMultiFileAsync(fileDetails);
                return Ok();
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Download File
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile")]
        public async Task<ActionResult> DownloadFile(int id)
        {
            if (id < 1)
            {
                return BadRequest();
            }
            try
            {
                await _uploadService.DownloadFileById(id);
                return Ok();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

Step 7

Configure a few services in the Program Class and inside the DI Container.

C#
 
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();

Step 8

Create a new database inside SQL Server and name it FileUploadDemo.

Step 9

Next, create the FileDetails table using the following script.

SQL
 
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

Step 10

Put the database connection inside the appsettings.json file.

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

Step 11

Finally, we run the application.

Run the application

Step 12

Now, we will upload a single file using swagger by providing the file and type of file based on the enum id.

Now, we are going to upload a single file using swagger by providing the file and type of file based on the enum id.

Step 13

Also, for uploading multiple files, we use Postman. Here you can see we use an array index to send the file and its type, which will work fine.

Here you can see we use an array index to send the file and its type and it will work fine.

Step 14

Later on, based on the file id, we are able to download files on the local system at a specified path location.

Later on, based on the file id, we are able to download files on the local system at a specified path location.

Step 15

Here you can see the downloaded file at the specified location.


The downloaded file at the specified location.

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

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

GitHub URL

Conclusion

This article discussed single and multiple file uploads using IFormFile and step-by-step implementation using the.NET Core Web API. We also read and saved files from the database to the specified location.

Happy Learning!

API Upload Web API Net (command)

Published at DZone with permission of Jaydeep Patil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Designing API-First EMR Architectures in .NET: Enabling Modular Growth in Compliance-Driven Systems
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI
  • Microservices With .NET Core: Building Scalable and Resilient Applications

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook