Tuesday, 12 September 2023

Adding File Zip Support to ASP.NET Core Web API

Leave a Comment

There are various phases involved in implementing file zip capabilities in an ASP.NET Core Web API. We will go over each step in this article, including setting up the project, creating the API endpoint, and generating a zip file containing numerous files.


Step 1: Begin by creating a new ASP.NET Core Web API Project.
Create a new ASP.NET Core Web API project in Visual Studio. You can do so by going to File > New > Project and then selecting "ASP.NET Core Web Application."

Step 2: Install the Necessary Packages
To work with zip files in your project, you'll need to include the System.IO.Compression library. Run the following command in the NuGet Package Manager Console:

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.

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;


[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:

[
    {
        "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. 

Best ASP.NET Core 8.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment