将文件下载为 ASP.NET Core 中的 zip

Download the file as a zip in ASP.NET Core

我正在设计一个教育网站。当用户下载一个培训课程时,我希望这个下载(培训课程)以压缩(zipper)的形式进行,请给出解决方案

我的代码:

  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;
    }

我写了一个演示来展示如何从 .net 核心下载 zip 文件:

首先,添加NuGet包SharpZipLib,在wwwroot中创建一个Image文件夹,并在里面放一些图片。

控制器

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);
        }
    }

当我点击 downloadZip 时,它会下载一个 .zip 文件

下面的简单示例说明了 static ZipFile.CreateFromDirectory 方法的使用,尽管它位于 System.IO.Compression 命名空间中,但实际上驻留在 System.IO.Compression.FileSystem 程序集中,因此您需要在控制器中添加对它的引用。

[HttpPost]
public FileResult Download()
{
    List<string> files = new List<string> { "filepath1", "filepath2" };
    var archive = Server.MapPath("~/archive.zip");
    var temp = Server.MapPath("~/temp");

    // clear any existing archive
    if (System.IO.File.Exists(archive))
    {
        System.IO.File.Delete(archive);
    }
    // empty the temp folder
    Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f));

    // copy the selected files to the temp folder
    files.ForEach(f => System.IO.File.Copy(f, Path.Combine(temp, Path.GetFileName(f))));

    // create a new archive
    ZipFile.CreateFromDirectory(temp, archive);

    return File(archive, "application/zip", "archive.zip");
}

来自来源的回答 - MikesDotNetting