Today, we are going to cover uploading & downloading multiple files using ASP.Net Core 5.0 web API by a simple process.
Note
Since I have the latest .Net 5.0 installed on my machine I used this. This same technique works in .Net Core 3.1 and .Net Core 2.1 as well.
Begin with creating an empty web API project in visual studio and for target framework choose .Net 5.0.
No external packages were used in this project.
Create a Services folder and inside that create one FileService class and IFileService Interface in it.
We have used three methods in this FileService.cs
  • UploadFile
  • DownloadFile
  • SizeConverter
Since we need a folder to store these uploading files, here we have added one more parameter to pass the folder name as a string where it will store all these files.
FileService.cs
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.IO.Compression;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. namespace UploadandDownloadFiles.Services
  10. {
  11. public class FileService :IFileService
  12. {
  13. #region Property
  14. private IHostingEnvironment _hostingEnvironment;
  15. #endregion
  16. #region Constructor
  17. public FileService(IHostingEnvironment hostingEnvironment)
  18. {
  19. _hostingEnvironment = hostingEnvironment;
  20. }
  21. #endregion
  22. #region Upload File
  23. public void UploadFile(List<IFormFile> files, string subDirectory)
  24. {
  25. subDirectory = subDirectory ?? string.Empty;
  26. var target = Path.Combine(_hostingEnvironment.ContentRootPath, subDirectory);
  27. Directory.CreateDirectory(target);
  28. files.ForEach(async file =>
  29. {
  30. if (file.Length <= 0) return;
  31. var filePath = Path.Combine(target, file.FileName);
  32. using (var stream = new FileStream(filePath, FileMode.Create))
  33. {
  34. await file.CopyToAsync(stream);
  35. }
  36. });
  37. }
  38. #endregion
  39. #region Download File
  40. public (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory)
  41. {
  42. var zipName = $"archive-{DateTime.Now.ToString("yyyy_MM_dd-HH_mm_ss")}.zip";
  43. var files = Directory.GetFiles(Path.Combine(_hostingEnvironment.ContentRootPath, subDirectory)).ToList();
  44. using (var memoryStream = new MemoryStream())
  45. {
  46. using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
  47. {
  48. files.ForEach(file =>
  49. {
  50. var theFile = archive.CreateEntry(file);
  51. using (var streamWriter = new StreamWriter(theFile.Open()))
  52. {
  53. streamWriter.Write(File.ReadAllText(file));
  54. }
  55. });
  56. }
  57. return ("application/zip", memoryStream.ToArray(), zipName);
  58. }
  59. }
  60. #endregion
  61. #region Size Converter
  62. public string SizeConverter(long bytes)
  63. {
  64. var fileSize = new decimal(bytes);
  65. var kilobyte = new decimal(1024);
  66. var megabyte = new decimal(1024 * 1024);
  67. var gigabyte = new decimal(1024 * 1024 * 1024);
  68. switch (fileSize)
  69. {
  70. case var _ when fileSize < kilobyte:
  71. return $"Less then 1KB";
  72. case var _ when fileSize < megabyte:
  73. return $"{Math.Round(fileSize / kilobyte, 0, MidpointRounding.AwayFromZero):##,###.##}KB";
  74. case var _ when fileSize < gigabyte:
  75. return $"{Math.Round(fileSize / megabyte, 2, MidpointRounding.AwayFromZero):##,###.##}MB";
  76. case var _ when fileSize >= gigabyte:
  77. return $"{Math.Round(fileSize / gigabyte, 2, MidpointRounding.AwayFromZero):##,###.##}GB";
  78. default:
  79. return "n/a";
  80. }
  81. }
  82. #endregion
  83. }
  84. }
SizeConverter function is used to get the actual size of our uploading files to the server.
IFileService.cs
  1. using Microsoft.AspNetCore.Http;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace UploadandDownloadFiles.Services
  7. {
  8. public interface IFileService
  9. {
  10. void UploadFile(List<IFormFile> files, string subDirectory);
  11. (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory);
  12. string SizeConverter(long bytes);
  13. }
  14. }
Let's add this service dependency in a startup.cs file
Startup.cs
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.HttpsPolicy;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Hosting;
  8. using Microsoft.Extensions.Logging;
  9. using Microsoft.OpenApi.Models;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Threading.Tasks;
  14. using UploadandDownloadFiles.Services;
  15. namespace UploadandDownloadFiles
  16. {
  17. public class Startup
  18. {
  19. public Startup(IConfiguration configuration)
  20. {
  21. Configuration = configuration;
  22. }
  23. public IConfiguration Configuration { get; }
  24. // This method gets called by the runtime. Use this method to add services to the container.
  25. public void ConfigureServices(IServiceCollection services)
  26. {
  27. services.AddControllers();
  28. services.AddSwaggerGen(c =>
  29. {
  30. c.SwaggerDoc("v1", new OpenApiInfo { Title = "UploadandDownloadFiles", Version = "v1" });
  31. });
  32. services.AddTransient<IFileService, FileService>();
  33. }
  34. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  35. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  36. {
  37. if (env.IsDevelopment())
  38. {
  39. app.UseDeveloperExceptionPage();
  40. app.UseSwagger();
  41. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "UploadandDownloadFiles v1"));
  42. }
  43. app.UseHttpsRedirection();
  44. app.UseRouting();
  45. app.UseAuthorization();
  46. app.UseEndpoints(endpoints =>
  47. {
  48. endpoints.MapControllers();
  49. });
  50. }
  51. }
  52. }
Create a FileController & now inject this IFileService using Constructor injection inside this FileController.
FileController.cs
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel.DataAnnotations;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. using UploadandDownloadFiles.Services;
  11. namespace UploadandDownloadFiles.Controllers
  12. {
  13. [Route("api/[controller]")]
  14. [ApiController]
  15. public class FileController : ControllerBase
  16. {
  17. #region Property
  18. private readonly IFileService _fileService;
  19. #endregion
  20. #region Constructor
  21. public FileController(IFileService fileService)
  22. {
  23. _fileService = fileService;
  24. }
  25. #endregion
  26. #region Upload
  27. [HttpPost(nameof(Upload))]
  28. public IActionResult Upload([Required] List<IFormFile> formFiles, [Required] string subDirectory)
  29. {
  30. try
  31. {
  32. _fileService.UploadFile(formFiles, subDirectory);
  33. return Ok(new { formFiles.Count, Size = _fileService.SizeConverter(formFiles.Sum(f => f.Length)) });
  34. }
  35. catch (Exception ex)
  36. {
  37. return BadRequest(ex.Message);
  38. }
  39. }
  40. #endregion
  41. #region Download File
  42. [HttpGet(nameof(Download))]
  43. public IActionResult Download([Required]string subDirectory)
  44. {
  45. try
  46. {
  47. var (fileType, archiveData, archiveName) = _fileService.DownloadFiles(subDirectory);
  48. return File(archiveData, fileType, archiveName);
  49. }
  50. catch (Exception ex)
  51. {
  52. return BadRequest(ex.Message);
  53. }
  54. }
  55. #endregion
  56. }
  57. }
We can test our API's in both swagger and postman.
Upload And Download Multiple Files Using Web API
Here we see our two API's which we have created to upload and download, so let's test each of these individually.
Upload And Download Multiple Files Using Web API
Pass the folder name inside the subDirectory and add files below to save inside the server and under the folder name. In response we see the total count of our files and the actual size of our entire files.
Upload And Download Multiple Files Using Web API
Now will check with Download API. Since we have multiple files inside of our folder it will download as a Zip file where we need to extract that to check the files.
Upload And Download Multiple Files Using Web API
Git Hub Repo - Download Source Code
If you found this article helpful, Please give it a Upload And Download Multiple Files Using Web API
.... keep learning !!!