Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all I currently have it so my program creates a zip file with reports in the zip. My controller action returns a file which is the zip. I have this happening in the success of my ajax.
Now how could I in the next step maybe in the success or im not even sure where I should have it so I can call another method to unzip the files. Then open the files that were unzipped?

What would you all do?
Here is what I currently have
C#
$('#btnGetChecks').on('click', function () {
            var arrChkBoxes = [];
            var arrSelectedQIDs = [];
            //$('input:checked').each(function() {
            //});    with 0 -  ^(0|\+?[1-9]\d*)$         /^-?[0-9]+$/
            // $(this).val($(this).val().replace(/[^\d].+/, ""));
            // if (!(keyCode >= 48 && keyCode <= 57)
           
            // Turn all selected checkbox T/F values into QuoteIDs
            $("input:checked").each(function (index, value) {
                arrChkBoxes.push($(value).val());
            });
            // Push all QuoteIDs into new array
            $.each(arrChkBoxes, function (key, value) {
                if (IsPositiveInteger(value)) {
                    arrSelectedQIDs.push(value);
                }
            }); 

            $.ajax({
                type: "GET",
                url: "/Service/ExportFiles/",
                contentType: "application/json; charset=utf-8",
                traditional: true,
                data: { "quoteIDs": arrSelectedQIDs },
                success: function (data) {
                    window.location = '/Service/DownloadAsZip?mimeType=' + data;
                    //window.location = '/Service/UnZipDownload';
                },
                error: function (request, status, error) {
                    alert("Error Generating Files");
                        //+ request.responseText);
                }
            });
        });
[HttpGet]
        public void UnZipDownload()
        {
            if(TempData["ZipName"] != null)
            {
                string zipName = TempData["ZipName"] as string;
                string downloadPath = new KnownFolder(KnownFolderType.Downloads).Path;
                string filePath = new KnownFolder(KnownFolderType.Downloads).Path;
                downloadPath = Path.GetFullPath(downloadPath);
                //Make sure last char on path doesn't allow malicious code outside of it.
                if (!downloadPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
                    downloadPath += Path.DirectorySeparatorChar;

                using (ZipArchive archive = ZipFile.OpenRead(filePath + zipName))
                {
                    foreach(ZipArchiveEntry entry in archive.Entries)
                    {
                        if(entry.FullName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(filePath);
                        }
                    }
                }
            }
           
        }

        /* Uses System.IO.Compression Library */
        [HttpGet]
        public virtual ActionResult DownloadAsZip(string mimeType)
        {          
            if (TempData["Files"] != null)
            {
                List<ServiceFile> lstFiles = TempData["Files"] as List<ServiceFile>;
                byte[] bytearray = null;
                string timeNow = DateTime.Now.ToString("MM-dd-yyyy-HHmmss");
                string fileName = "Service" + timeNow + ".zip";

                using (MemoryStream ms = new MemoryStream())
                {
                    // Creates the .zip
                    using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                    {
                        foreach (ServiceFile file in lstFiles)  // iterate through each file
                        {
                            // Creates empty file and names it inside of .zip
                            ZipArchiveEntry zipItem = archive.CreateEntry(file.FileName + file.Extension);
                            // adds file to zipItem
                            using (MemoryStream ms4file = new MemoryStream(file.FileBytes))
                            {
                                using (Stream stream = zipItem.Open())
                                {
                                    ms4file.CopyTo(stream);
                                }
                            }
                        }
                    }
                    bytearray = ms.ToArray();
                }
                TempData["ZipName"] = fileName;
                return File(bytearray, "application/zip", fileName);
            }
            else
            {
                return new EmptyResult();
            }
        }


What I have tried:

I tried to do it in my success under the line that created but it went to the new method but then my zip wasn’t created.
Posted
Updated 8-Nov-19 9:33am

Your C# code is running on the server. It does not have access to the user's file system.

You cannot automatically unzip a file that the user has downloaded. You will have to let them unzip the file themselves.
 
Share this answer
 
This is the method i created which takes a zip file and unzips it and puts all the pdfs that were in the zip in the downloads directory.
My last step will now be to create a method that opens each PDF.
C#
[HttpGet]
        public void UnZipDownload()
        {
            if(TempData["ZipName"] != null)
            {
                string zipName = TempData["ZipName"] as string;
                string downloadPath = new KnownFolder(KnownFolderType.Downloads).Path;
                string filePath = new KnownFolder(KnownFolderType.Downloads).Path;
                downloadPath = Path.GetFullPath(downloadPath);
                //Make sure last char on path doesn't allow malicious code outside of it.
                if (!downloadPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
                    downloadPath += Path.DirectorySeparatorChar;

                using (ZipArchive archive = ZipFile.OpenRead(filePath + "\\" + zipName))
                {
                    foreach(ZipArchiveEntry entry in archive.Entries)
                    {
                        if(entry.FullName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
                        {
                            string destinationPath = Path.GetFullPath(Path.Combine(filePath, entry.FullName));

                            entry.ExtractToFile(destinationPath);
                           // entry.
                        }
                    }
                }
            }
           
        }
 
Share this answer
 
Comments
Dave Kreskowiak 8-Nov-19 19:49pm    
You posted this as an answer to your own question, NOT a response to someone else. Because of this, nobody got an notification that you posted anything.

This code runs entirely on the server, not the client. The code running in the browser on the client-side can NOT unzip a file and show content from what was unpacked. It will have no access to the client resources, like its file system.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900