Search code examples
c#asp.net-corerazor-pages

Download the file as a zip in ASP.NET Core


I am designing an educational site. When the user downloads a training course, I want this download (training course) to be done in the form of compression (zipper), please give a solution

My code:

  public Tuple<byte[],string,string> DownloadFile(long episodeId)
    {
        var episode=_context.CourseEpisodes.Find(episodeId);
        string filepath = Path.Combine(Directory.GetCurrentDirectory(), 
      "wwwroot/courseFiles",
            episode.FileName);
        string fileName = episode.FileName;
        if(episode.IsFree)
        {
            byte[] file = System.IO.File.ReadAllBytes(filepath);
           return Tuple.Create(file, "application/force-download",fileName);                   
        }
        if(_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
        {
           
     if(IsuserIncorse(_httpContextAccessor.HttpContext.User.Identity.Name, 
          episode.CourseId))
            {
                byte[] file = System.IO.File.ReadAllBytes(filepath);
          return Tuple.Create(file, "application/force-download", fileName);             
            }
        }
        return null;
    }

Solution

  • I write a demo to show how to download zip file from .net core:

    First , Add NuGet package SharpZipLib , create an Image Folder in wwwroot and put some picture in it.

    enter image description here

    controller

    public class HomeController : Controller
        {
            private IHostingEnvironment _IHosting;
    
            public HomeController(IHostingEnvironment IHosting)
            {
                _IHosting = IHosting;
            }
    
            public IActionResult Index()
            {
                return View();
            }
    
            public FileResult DownLoadZip()
            {
                var webRoot = _IHosting.WebRootPath;
                var fileName = "MyZip.zip";
                var tempOutput = webRoot + "/Images/" + fileName;
    
                using (ZipOutputStream IzipOutputStream = new ZipOutputStream(System.IO.File.Create(tempOutput)))
                {
                    IzipOutputStream.SetLevel(9);
                    byte[] buffer = new byte[4096];
                    var imageList = new List<string>();
    
                    imageList.Add(webRoot + "/Images/1202.png");
                    imageList.Add(webRoot + "/Images/1data.png");
                    imageList.Add(webRoot + "/Images/aaa.png");
    
                    for (int i = 0; i < imageList.Count; i++)
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(imageList[i]));
                        entry.DateTime= DateTime.Now;
                        entry.IsUnicodeText = true;
                        IzipOutputStream.PutNextEntry(entry);
    
                        using (FileStream oFileStream = System.IO.File.OpenRead(imageList[i]))
                        {
                            int sourceBytes;
                            do
                            { 
                                sourceBytes = oFileStream.Read(buffer, 0, buffer.Length);
                                IzipOutputStream.Write(buffer, 0, sourceBytes);
                            }while (sourceBytes > 0);
                        }
                    }
                    IzipOutputStream.Finish();
                    IzipOutputStream.Flush();
                    IzipOutputStream.Close();
                }
    
                byte[] finalResult = System.IO.File.ReadAllBytes(tempOutput);
                if (System.IO.File.Exists(tempOutput)) { 
                    System.IO.File.Delete(tempOutput);
                }
                if (finalResult == null || !finalResult.Any()) {
                    throw new Exception(String.Format("Nothing found"));
    
                }
    
                return File(finalResult, "application/zip", fileName);
            }
        }
    

    when I click the downloadZip ,it will download a .zip file

    enter image description here