【问题标题】:Download the file as a zip in ASP.NET Core在 ASP.NET Core 中以 zip 格式下载文件
【发布时间】:2021-12-07 07:11:08
【问题描述】:

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

我的代码:

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

【问题讨论】:

  • 您不能同时使用 ASP.NET Core 和古老的 ASP.NET MVC 4。您实际使用的是什么?
  • 不,我只使用 ASP.NET Core 和模板 RazorPage

标签: asp.net-core asp.net-core-razor-pages


【解决方案1】:

我编写了一个演示来展示如何从.net core 下载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文件

【讨论】:

    【解决方案2】:

    下面的简单示例说明了 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

    【讨论】:

      猜你喜欢
      • 2011-02-09
      • 2021-09-24
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多