In this article I will explain with an example, how to download Compressed Zip File archive from Web API in ASP.Net MVC Razor.
This article will make use of DotNetZip library for compressing files and creating Zip file in ASP.Net MVC Razor.
Multiple selected files in Folder (Directory) will be added to a Zip File and will be sent for download.
Adding reference of DotNetZip Library
The very first thing you will need to add reference of the DotNetZip Library in ASP.Net MVC project.
This can be done by right clicking References in the Solution Explorer and then clicking Add Reference option in the Context Menu and finally selecting the DotNetZip Library DLL.
Storage of Files on Server Directory
In my project, I have created a Folder named Files which contains the following files as shown in the screenshot below.
Model
The Model class consists of the following three properties.
public class FileModel
{
public string FileName { get; set; }
public string FilePath { get; set; }
public bool IsSelected { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.IO;
using Ionic.Zip;
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, the files are read from the Folder and the details of the File such as the Name and its Path are added to a Generic List collection of the FileModel class.
Finally, the Generic List collection of the FileModel class is returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Files/"));
List<FileModel> files = new List<FileModel>();
foreach (string filePath in filePaths)
{
files.Add(new FileModel()
{
FileName = Path.GetFileName(filePath),
FilePath = filePath
});
}
return View(files);
}
}
Web API Controller
The Web API Controller handles the POST operation and when the form is submitted, a Generic List collection of the FileModel class object is received as parameter in this method.
First an object of the DotNetZip Library is created and a loop is executed over the objects of the received Generic List collection of the FileModel class.
If the IsSelected property is True i.e. the CheckBox is checked for the file, then the file is added to the object of the DotNetZip Library.
Finally, the DotNetZip Library object is downloaded as Zip file.
public class ZipAPIController : ApiController
{
[HttpPost]
[Route("api/ZipAPI/DownloadZipFile")]
public HttpResponseMessage DownloadZipFile(List<FileModel> files)
{
//Create HTTP Response.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
//Create the Zip File.
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
foreach (FileModel file in files)
{
if (file.IsSelected)
{
zip.AddFile(file.FilePath, "Files");
}
}
//Set the Name of Zip File.
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Zip File to MemoryStream.
zip.Save(memoryStream);
//Set the Response Content.
response.Content = new ByteArrayContent(memoryStream.ToArray());
//Set the Response Content Length.
response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
}
}
}
View
Inside the View, the FileModel class is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the File records.
The View consists of an HTML Form, which will POST the data to the Web API Controller’s Action method.
There is also Submit button which when clicked, the Form gets submitted.
@using Download_Zip_Files_WebAPI_MVC.Models
@model List<FileModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
table {
border: 1px solid #ccc;
border-collapse: collapse;
}
table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th, table td {
padding: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
@using (Html.BeginForm("", "api/ZipAPI/DownloadZipFile", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th></th>
<th>File Name</th>
</tr>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>@Html.CheckBoxFor(m => m[i].IsSelected)</td>
<td>
@Model[i].FileName
@Html.HiddenFor(m => m[i].FilePath)
@Html.HiddenFor(m => m[i].FileName)
</td>
</tr>
}
</table>
<br/>
<input type="submit" value="Download"/>
}
</body>
</html>
Screenshot
Downloads