Creating Zip file from stream and downloading it

前端 未结 8 1101
深忆病人
深忆病人 2020-12-02 22:20

I have a DataTable that i want to convert it to xml and then zip it, using DotNetZip. finally user can download it via Asp.Net webpage. My code in below

            


        
相关标签:
8条回答
  • 2020-12-02 23:10

    Add a ContentType header:

    Response.ContentType = "application/zip";
    

    this will allow the browsers to detect what you are sending.

    0 讨论(0)
  • 2020-12-02 23:12

    This code will help you in downloading a file from stream.

    using (var outStream = new MemoryStream())
    {
        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
        {
            var fileInArchive = archive.CreateEntry("FileName.pdf", CompressionLevel.Optimal);
            using (var entryStream = fileInArchive.Open())
            using (WebResponse response = req.GetResponse())
            {
                using (var fileToCompressStream = response.GetResponseStream())
                {
                    fileToCompressStream.CopyTo(entryStream);
                }
            }                       
        }
        using (var fileStream = new FileStream(@"D:\test.zip", FileMode.Create))
        {
            outStream.Seek(0, SeekOrigin.Begin);
            outStream.CopyTo(fileStream);
        }
    }
    

    Namespaces needed:

    using System.IO.Compression;
    using System.IO.Compression.ZipArchive;
    
    0 讨论(0)
提交回复
热议问题