Introduction
In this article, we will create a demo for copying images from another folder and downloading those images in zip format. We have to follow some simple steps to create a project and export some files in zip format in ASP.NET.
Step 1 – Create a Project
After opening Visual Studio, next, we need to create an ASP.NET MVC project. For doing that, just click File – New – Project.
After choosing a project, a new dialog will pop up. In that, select ASP.NET Web Application in the Web tab and give your project the location and a name. Then, click the “Ok” button. Choose the MVC Template.
Step 2: Install the SharpZipLib Nuget Package
For Installing the SharpZipLib NuGet package, open the NuGet Package Manager from right-clicking on References and select the “Manage NuGet Package” option. Then, perform the following steps.
Step 3 – Create a Method in Controller for Downloading the zip file
Write this code into your Controller and give image path into ImageList for images that you want to download in the zip file and create a folder named TempImages in the root directory.
Right now, I gave the static image path but you can set a dynamic image path according to your requirements.
public FileResult DownloadZipFile() { var fileName = string.Format("{0}_ImageFiles.zip", DateTime.Today.Date.ToString("dd-MM-yyyy") + "_1"); var tempOutPutPath = Server.MapPath(Url.Content("/TempImages/")) + fileName; using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(tempOutPutPath))) { s.SetLevel(9); // 0-9, 9 being the highest compression byte[] buffer = new byte[4096]; var ImageList = new List<string>(); ImageList.Add(Server.MapPath("/Images/01.jpg")); ImageList.Add(Server.MapPath("/Images/02.jpg")); for (int i = 0; i < ImageList.Count; i++) { ZipEntry entry = new ZipEntry(Path.GetFileName(ImageList[i])); entry.DateTime = DateTime.Now; entry.IsUnicodeText = true; s.PutNextEntry(entry); using (FileStream fs = System.IO.File.OpenRead(ImageList[i])) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } s.Finish(); s.Flush(); s.Close(); } byte[] finalResult = System.IO.File.ReadAllBytes(tempOutPutPath); if (System.IO.File.Exists(tempOutPutPath)) System.IO.File.Delete(tempOutPutPath); if (finalResult == null || !finalResult.Any()) throw new Exception(String.Format("No Files found with Image")); return File(finalResult, "application/zip", fileName); }
Step 4 – Call the DownloadZipFile() method from the view side
In this line, I have set the link named Download zip and called the DownloadZipFile() method.
<a href="Home/DownloadZipFile/" target="_blank" class="btn btn-primary" style="margin-top:20px;">Download Zip</a>
After clicking on it, the zip file will be download.
Output :