Creating a File Zip Functionality in ASP.NET Core Web API

Introduction

Creating a file zip functionality in an ASP.NET Core Web API involves several steps. In this article, we will go through each step, including setting up the project, creating the API endpoint, and generating a zip file containing multiple files.

Step 1. Create a new ASP.NET Core Web API Project

Open Visual Studio and create a new ASP.NET Core Web API project. You can do this by selecting File > New > Project, then choosing "ASP.NET Core Web Application."

Step 2. Install Required Packages

In your project, you will need to install the System.IO.Compression library for working with zip files. Open the NuGet Package Manager Console and run the following command:

Install-Package System.IO.Compression.ZipFile

This package allows you to create and manipulate zip files in your ASP.NET Core application.

Step 3. Create a Model

Create a model class to represent the files you want to include in the zip file. For this example, let's assume you want to zip together image files.

Author: Sardar Mudassar Ali Khan
public class FileItem
{
    public string FileName { get; set; }
    public byte[] Content { get; set; }
}

Step 4. Create a Controller

Create a controller that will handle the zip file creation. Right-click on the Controllers folder in your project and select  Add > Controller. Name it ZipController.cs.

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

Author: Sardar Mudassar Ali Khan
[Route("api/[controller]")]
[ApiController]
public class ZipController : ControllerBase
{
    [HttpPost]
    [Route("createzip")]
    public async Task<IActionResult> CreateZipAsync([FromBody] List<FileItem> files)
    {
        if (files == null || files.Count == 0)
            return BadRequest("No files provided for zipping.");

        // Create a temporary memory stream for the zip file
        using var memoryStream = new MemoryStream();

        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in files)
            {
                var entry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
                using var entryStream = entry.Open();
                await entryStream.WriteAsync(file.Content, 0, file.Content.Length);
            }
        }

        memoryStream.Seek(0, SeekOrigin.Begin);

        // Generate the HTTP response with the zip file
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(memoryStream);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "download.zip"
        };

        return File(memoryStream, "application/zip", "download.zip");
    }
}

Step 5. Test the API

You can test the API using a tool like Postman or by creating a simple client application. Make a POST request to https://yourdomain/api/zip/createzip with a JSON body containing the list of files you want to include in the zip.

Example JSON request body:

Author: Sardar Mudassar Ali Khan
[
    {
        "FileName": "image1.jpg",
        "Content": "BASE64_ENCODED_IMAGE_DATA"
    },
    {
        "FileName": "image2.jpg",
        "Content": "BASE64_ENCODED_IMAGE_DATA"
    }
]

Replace BASE64_ENCODED_IMAGE_DATA with the actual base64-encoded content of your files.

Step 6. Run the Application

  • Build and run your ASP.NET Core Web API project. You can use tools like Postman or Swagger UI to test the CreateZipAsync endpoint.
  • When you make a POST request to the endpoint with the list of files, it will generate a zip file containing those files and return it as a downloadable attachment.
  • That's it. You've successfully created a Web API in ASP.NET Core for creating zip files with multiple files inside.

Conclusion

In this article, we walked through the process of creating a file zip functionality in an ASP.NET Core Web API. We covered all the necessary steps, from setting up the project to creating the API endpoint and generating multiple zip files. By following these steps, you can easily implement file compression and allow your users to download zipped files from your API. Whether you're building a document management system, a file-sharing platform, or any application that deals with multiple files, this guide should help you get started with zip functionality in your ASP.NET Core Web API.


Similar Articles