Download archive from ASP.NET web application

Download archive from the server

It is a common feature for web applications to download a file from your web server. To reduce data size transferred over wire you may want to compress the file. It is convenient for a user to choose the format of the archive to download. This sample gives you some insights on how to manage it.

Prepare ASP.NET Web Application

Using Visual Studio compose ASP.NET Core Web Application. Let it be a simple Web Application with Razor Pages. Using NuGet Package Manager you include two packages for your project: Aspose.Zip for compression and Aspose.BarCode for generation sample data.
Find page Index.cshtml within your Solution Explorer. Now, add a form to that page with a submit button within it. It needed to initiate download request by user. Add to that page following HTML markup:

<form method="post">    
    <input type="submit" value="Download" />

List archive formats

For this sample, we chosen three of archive formats Aspose.ZIP supports: ZIP, Bzip2, 7z. Compose enumeration for those formats marking its members with DisplayAttribute
The enumeration code will be:

public enum ArchiveFormat
    [Display(Name = "ZIP")]

    [Display(Name = "Bzip2")]

    [Display(Name = "7z")]

Next, you need to create a dropdown list within the web form. It is pretty simple with GetEnumSelectList Html helper - no need to generate items with a loop. Just put inside your form on Index.cshtml following snippet:

<select name="archiveFormat" asp-items="Html.GetEnumSelectList<ArchiveFormat>()"></select>

Run the application and look to the index page. You’ll see something like that:

Handling user request

So,the user specify desired archive format and hits “Download”. How to handle his request on the server-side? Using ASP.NET approach we need to compose an appropriate OnPost method to Index.cshtml.cs source. Here is the draft of the method:

public FileStreamResult OnPost([FromForm] ArchiveFormat archiveFormat)
  switch (archiveFormat)
     case ArchiveFormat.Zip:
       return new FileStreamResult(result, "application/zip") {FileDownloadName = ""};
     case ArchiveFormat.Bzip2:
       return new FileStreamResult(result, "application/x-bzip2") {FileDownloadName = "barcode.bmp.bz2"};
     case ArchiveFormat.SevenZip:
       return new FileStreamResult(result, "application/x-7z-compressed") {FileDownloadName = "barcode.7z"};                           

So for the requested archive type we must prepare the corresponding archive from sample data (result variable) and respond with Microsoft.AspNetCore.Mvc.FileStreamResult having the proper MIME type.

Generating sample data

We use Aspose.BarCode library to generate BMP image of barcode using this instruction. The snippet of data stream generation:

Finishing response

Now we have a raw data stream from the GenerateBarcode method. Compress it appropriately in every case. Below is the final OnPost method.