Sunday, June 14, 2015

Download multiple files as a Zip file with Asp.Net

While doing project, you may need load system to multiple files. After saving it, you may  need to download them to your PC. You can download them as  a Zip by using Asp.Net.

Initially in View, define button that triggers to download files.

<a href="@Url.Action("ControllerMethod", "ControllerName", new {id = 12})" class="btn btn-success"><i class="fa fa-download"></i> Export File </a>

  • In View, like above, we define button which trigger the method in Controller. In @Url.Action firstly define Controlller method name, after that,  define Controller name. If we want to  send parameter to controller method, wecan specify it like this 'new {id=12} '. Use <i class="fa fa-download"></i>  to get an download icon object on button.

In Controller:

      You can reach parameter value with id which we can specify like this in View. To get Zip file we should include System.IO.Compression namespace and add System.IO.Compression.dll to project.
We will use ZipArchive.CreateEntry method to create an empty entry in the zip archive.
To get more please visit link.

 
public ActionResult ControllerMethod(int id)
        {


            using (var compressedFileStream = new MemoryStream())
            {

                using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
                {

                    //get list of file
                    var listOfFile = _servis.GetListOfFiles(id);

                    int i = 1;

                   //loop all  the files which export
                   
             foreach (var file in listOfFile )
                 {
                 //get file name
                  string fileName = file.fileName;
                                            
                        var zipEntry11 = zipArchive.CreateEntry(fileName);

                        if (file != null)
                        {
                          //get file content
                          using (var originalFileStream = new MemoryStream(file.fileContent.ToArray()))
                            {

                            using (var zipEntryStream = zipEntry11.Open())
                            {
                            await originalFileStream.CopyToAsync(zipEntryStream);
                            }
                           }
                        }
                        i++;
                    }

                }

                //Add multiple file in a zip file
                return File(compressedFileStream.ToArray(), "application/zip",    "FileName.zip");
            }
        }


No comments:

Post a Comment