使用 Web API 上傳和下載多個檔案

使用 Web API 上傳和下載多個檔案

透過一個簡單的過程介紹使用 ASP.NET Core 6.0 Web API 上傳和下載多個檔案。

最後更新 2022/7/23 上午9:37
Jay Krishna Reddy
預計閱讀 5 分鐘
分類
ASP.NET Core
標籤
.NET C# ASP.NET Core Web API

原文作者:Jay Krishna Reddy

原文連結:https://www.c-sharpcorner.com/article/upload-and-download-multiple-files-using-web-api/

翻譯:沙漠盡頭的狼(Google翻譯加持,文中版本使用.NET 6 升級)

---正文開始---

今天,我們將透過一個簡單的過程介紹使用 ASP.NET Core 6.0 Web API 上傳和下載多個檔案。

步驟

首先在 Visual Studio 中建立一個空的 Web API 專案,目標框架選擇 .NET 6.0

此專案中沒有使用外部套件。

建立一個 Services 資料夾,並在其中建立一個 FileService 類別和 IFileService 介面。

我們在這個 FileService.cs 中使用了三個方法

  • UploadFile
  • DownloadFile
  • SizeConverter

由於我們需要一個資料夾來儲存這些上傳檔案,因此我們在這裡新增了一個參數來將資料夾名稱作為字串傳遞,它將會儲存所有上傳的這些檔案。

FileService.cs

using System.IO.Compression;

namespace FileUploadAndDownload.Services;

public class FileService : IFileService
{
    #region Property

    private readonly IWebHostEnvironment _webHostEnvironment;

    #endregion

    #region Constructor

    public FileService(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment = webHostEnvironment;
    }

    #endregion

    #region Upload File

    public void UploadFile(List<IFormFile> files, string subDirectory)
    {
        subDirectory = subDirectory ?? string.Empty;
        var target = Path.Combine(_webHostEnvironment.ContentRootPath, subDirectory);

        Directory.CreateDirectory(target);

        files.ForEach(async file =>
        {
            if (file.Length <= 0) return;
            var filePath = Path.Combine(target, file.FileName);
            await using var stream = new FileStream(filePath, FileMode.Create);
            await file.CopyToAsync(stream);
        });
    }

    #endregion

    #region Download File

    public (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory)
    {
        var zipName = $"archive-{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.zip";

        var files = Directory.GetFiles(Path.Combine(_webHostEnvironment.ContentRootPath, subDirectory)).ToList();

        using var memoryStream = new MemoryStream();
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            files.ForEach(file =>
            {
                var theFile = archive.CreateEntry(Path.GetFileName(file));
                using var binaryWriter = new BinaryWriter(theFile.Open());
                binaryWriter.Write(File.ReadAllBytes(file));
            });
        }

        return ("application/zip", memoryStream.ToArray(), zipName);
    }

    #endregion

    #region Size Converter

    public string SizeConverter(long bytes)
    {
        var fileSize = new decimal(bytes);
        var kilobyte = new decimal(1024);
        var megabyte = new decimal(1024 * 1024);
        var gigabyte = new decimal(1024 * 1024 * 1024);

        return fileSize switch
        {
            _ when fileSize < kilobyte => "Less then 1KB",
            _ when fileSize < megabyte =>
                $"{Math.Round(fileSize / kilobyte, 0, MidpointRounding.AwayFromZero):##,###.##}KB",
            _ when fileSize < gigabyte =>
                $"{Math.Round(fileSize / megabyte, 2, MidpointRounding.AwayFromZero):##,###.##}MB",
            _ when fileSize >= gigabyte =>
                $"{Math.Round(fileSize / gigabyte, 2, MidpointRounding.AwayFromZero):##,###.##}GB",
            _ => "n/a"
        };
    }

    #endregion
}

SizeConverter 函式用於取得我們上傳檔案到伺服器的實際大小。

IFileService.cs

namespace FileUploadAndDownload.Services;

public interface IFileService
{
    void UploadFile(List<IFormFile> files, string subDirectory);
    (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory);
    string SizeConverter(long bytes);
}

讓我們在 Program.cs 檔案中新增這個服務相依性

Program.cs

using FileUploadAndDownload.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.AddTransient<IFileService, FileService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

建立一個 FileController,並在 FileController 中的建構函式注入 IFileService

FileController.cs

using FileUploadAndDownload.Services;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace FileUploadAndDownload.Controllers;

[Route("api/[controller]")]
[ApiController]
public class FileController : ControllerBase
{
    private readonly IFileService _fileService;

    public FileController(IFileService fileService)
    {
        _fileService = fileService;
    }

    [HttpPost(nameof(Upload))]
    public IActionResult Upload([Required] List<IFormFile> formFiles, [Required] string subDirectory)
    {
        try
        {
            _fileService.UploadFile(formFiles, subDirectory);

            return Ok(new { formFiles.Count, Size = _fileService.SizeConverter(formFiles.Sum(f => f.Length)) });
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

    [HttpGet(nameof(Download))]
    public IActionResult Download([Required] string subDirectory)
    {
        try
        {
            var (fileType, archiveData, archiveName) = _fileService.DownloadFiles(subDirectory);

            return File(archiveData, fileType, archiveName);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }
}

我們可以在 swaggerpostman 中測試我們的 API。

在這裡,我們看到了我們建立的用於上傳和下載的兩個 API,因此讓我們分別測試它們中的每一個。

subDirectory 欄位中輸入檔案儲存的資料夾名稱,並在下面新增檔案用於儲存在伺服器對應的子資料夾名稱下。作為回應,我們會看到檔案的總數和所有上傳檔案的總實際大小。

現在將檢查下載 API。由於我們的資料夾中有多個檔案,它將會以 Zip 檔案格式下載,我們需要將其解壓縮以檢查檔案。

總結

使用 Web API 介面的方式上傳和下載檔案,適用於 Blazor Server、Blazor Client、MAUI、Winform、WPF 等用戶端程式,之後有空再寫寫用戶端如何呼叫這些介面。

.... 保持學習 !!!

繼續探索

延伸閱讀

更多文章
同分類 / 同標籤 2022/4/13

ASP.NET Core WebApi 回傳結果統一包裝實務

關於 WebApi 統一結果回傳的時候,讓我也有了更進一步的思考,首先是如何能更好的限制回傳統一的格式,其次是關於結果的包裝一定是更簡單更強大。在不斷的思考和完善中,終於有了初步的成果,便分享出來,學無止境思考便無止境,希望以此能與君共勉。

繼續閱讀