2012-04-04 34 views
5

Về cơ bản, người dùng có thể nhấp vào một liên kết và tải xuống nhiều tệp pdf. Nhưng Catch là tôi không thể tạo tập tin trên máy chủ hoặc bất cứ nơi nào. Mọi thứ đều có trong ký ức.Tạo tệp Zip từ luồng bộ nhớ C#

Tôi có thể tạo luồng bộ nhớ và Response.Flush() dưới dạng pdf nhưng làm cách nào để nén nhiều luồng bộ nhớ mà không tạo tệp.

Đây là mã của tôi:

Response.ContentType = "application/zip"; 

      // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that 
      // Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer. 
      Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\""); 
      Response.CacheControl = "Private"; 
      Response.Cache.SetExpires(DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition     

      byte[] abyBuffer = new byte[4096]; 

      ZipOutputStream outStream = new ZipOutputStream(Response.OutputStream); 

      outStream.SetLevel(3); 

      #region Repeat for each Memory Stream 
      MemoryStream fStream = CreateClassroomRoster();// This returns a memory stream with pdf document 

      ZipEntry objZipEntry = new ZipEntry(ZipEntry.CleanName("ClassroomRoster.pdf")); 

      objZipEntry.DateTime = DateTime.Now; 

      objZipEntry.Size = fStream.Length; 

      outStream.PutNextEntry(objZipEntry); 

      int count = fStream.Read(abyBuffer, 0, abyBuffer.Length); 

      while (count > 0) 
      { 
       outStream.Write(abyBuffer, 0, count); 

       count = fStream.Read(abyBuffer, 0, abyBuffer.Length); 

       if (!Response.IsClientConnected) 
       { 
        break; 
       } 

       Response.Flush(); 
      } 

      fStream.Close(); 
      #endregion 

      outStream.Finish(); 
      outStream.Close(); 

      Response.Flush(); 
      Response.End(); 

này tạo ra một file zip nhưng không có tập tin bên trong nó

Tôi đang sử dụng sử dụng iTextSharp.text - để tạo pdf sử dụng ICSharpCode.SharpZipLib.Zip - cho Zipping

Xin cảm ơn, Kavita

+0

Bạn đã bao giờ tìm thấy giải pháp chưa? Tôi cần phải làm điều tương tự này. – sbonkosky

+0

không có tôi không .. Tôi đã thử mọi giải pháp trực tuyến nhưng không có gì làm việc .. hy vọng u tìm thấy nó – Arshya

+0

Liên kết này có thể giúp: http://snipplr.com/view/47762/ – updev

Trả lời

13

Liên kết này mô tả cách tạo một zip từ MemoryStream bằng SharpZipLib: https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples#wiki-anchorMemory. Sử dụng điều này và iTextSharp, tôi đã có thể nén nhiều tệp PDF được tạo trong bộ nhớ.

Đây là mã của tôi:

 MemoryStream outputMemStream = new MemoryStream(); 
     ZipOutputStream zipStream = new ZipOutputStream(outputMemStream); 

     zipStream.SetLevel(3); //0-9, 9 being the highest level of compression 
     byte[] bytes = null; 

     // loops through the PDFs I need to create 
     foreach (var record in records) 
     { 
      var newEntry = new ZipEntry("test" + i + ".pdf"); 
      newEntry.DateTime = DateTime.Now; 

      zipStream.PutNextEntry(newEntry); 

      bytes = CreatePDF(++i); 

      MemoryStream inStream = new MemoryStream(bytes); 
      StreamUtils.Copy(inStream, zipStream, new byte[4096]); 
      inStream.Close(); 
      zipStream.CloseEntry(); 

     } 

     zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. 
     zipStream.Close();   // Must finish the ZipOutputStream before using outputMemStream. 

     outputMemStream.Position = 0; 

     return File(outputMemStream.ToArray(), "application/octet-stream", "reports.zip"); 

Các CreatePDF Phương pháp:

private static byte[] CreatePDF(int i) 
    { 
     byte[] bytes = null; 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      Document document = new Document(PageSize.A4, 25, 25, 30, 30); 
      PdfWriter writer = PdfWriter.GetInstance(document, ms); 
      document.Open(); 
      document.Add(new Paragraph("Hello World " + i)); 
      document.Close(); 
      writer.Close(); 
      bytes = ms.ToArray(); 
     } 
     return bytes; 

    } 
+0

Cảm ơn câu trả lời vì nó đã làm việc cho tôi cũng. Bạn có thể vui lòng cho tôi biết cách tôi có thể nén tệp văn bản không? –

+0

hoạt động giống như một sự quyến rũ! cảm ơn. – ahmet

0

Bạn có thể tạo ra file pdf của bạn và lưu nó trong IsolatedStorageFileStream sau đó bạn có thể nén nội dung từ lưu trữ đó.

0

Mã này sẽ giúp bạn trong việc tạo Zip bằng nhiều tệp pdf mà bạn sẽ nhận được Mỗi tệp từ Liên kết tải xuống.

 using (var outStream = new MemoryStream()) 
       { 
        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true)) 
        { 
         for (String Url in UrlList) 
         { 
          WebRequest req = WebRequest.Create(Url); 
          req.Method = "GET"; 
          var fileInArchive = archive.CreateEntry("FileName"+i+ ".pdf", CompressionLevel.Optimal); 
          using (var entryStream = fileInArchive.Open()) 
          using (WebResponse response = req.GetResponse()) 
          { 
           using (var fileToCompressStream = response.GetResponseStream()) 
           { 
            entryStream.Flush(); 
            fileToCompressStream.CopyTo(entryStream); 
            fileToCompressStream.Flush(); 
           } 
          } 
          i++; 
         } 

        } 
        using (var fileStream = new FileStream(@"D:\test.zip", FileMode.Create)) 
        { 
         outStream.Seek(0, SeekOrigin.Begin); 
         outStream.CopyTo(fileStream); 
        } 
       } 

Namespace cần thiết: System.IO.Compression; System.IO.Compression.ZipArchive;

0

Dưới đây là mã tạo tệp zip trong MemoryStream bằng lớp ZipOutputStream tồn tại bên trong tệp ICSharpCode.SharpZipLib.

FileStream fileStream = File.OpenRead(@"G:\1.pdf"); 
MemoryStream MS = new MemoryStream(); 

byte[] buffer = new byte[fileStream.Length]; 
int byteRead = 0; 

ZipOutputStream zipOutputStream = new ZipOutputStream(MS); 
zipOutputStream.SetLevel(9); //Set the compression level(0-9) 
ZipEntry entry = new ZipEntry(@"1.pdf");//Create a file that is needs to be compressed 
zipOutputStream.PutNextEntry(entry);//put the entry in zip 

//Writes the data into file in memory stream for compression 
while ((byteRead = fileStream.Read(buffer, 0, buffer.Length)) > 0) 
    zipOutputStream.Write(buffer, 0, byteRead); 

zipOutputStream.IsStreamOwner = false; 
fileStream.Close(); 
zipOutputStream.Close(); 
MS.Position = 0; 
Các vấn đề liên quan