首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ASP.NET核心中以压缩方式下载该文件

在ASP.NET核心中以压缩方式下载该文件
EN

Stack Overflow用户
提问于 2021-12-07 07:11:08
回答 2查看 4.5K关注 0票数 -1

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

我的代码:

代码语言:javascript
复制
  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;
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-07 08:59:08

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

First,添加NuGet package SharpZipLib,在wwwroot中创建Image文件夹,并在其中放置一些图片。

控制器

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2021-12-07 10:45:30

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

代码语言:javascript
复制
[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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70256149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档