2012-09-24 25 views
2

我在MVC3中使用心愛的DotNetZip存檔庫來生成Zip文件,其中包含存儲在數據庫中的二進制文件的.png圖像。然後我將流生成的Zip文件流出供用戶下載。 (我在保存到數據庫之前驗證圖像數據,因此您可以假設所有圖像數據都是有效的)。創建並傳輸圖像存檔zip文件以供下載C#

public ActionResult PictureExport() 
     { 
      IEnumerable<UserPicture> userPictures = db.UserPicture.ToList(); 
      //"db" is a DataContext and UserPicture is the model used for uploaded pictures. 
      DateTime today = DateTime.Now; 
      string fileName = "attachment;filename=AllUploadedPicturesAsOf:" + today.ToString() + ".zip"; 
      this.Response.Clear(); 
      this.Response.ContentType = "application/zip"; 
      this.Response.AddHeader("Content-Disposition", fileName); 

      using (ZipFile zipFile = new ZipFile()) 
      { 
       using (MemoryStream stream = new MemoryStream()) 
       { 
       foreach (UserPicture userPicture in userPictures) 
        { 
        stream.Seek(0, SeekOrigin.Begin); 
        string pictureName = userPicture.Name+ ".png"; 
        using (MemoryStream tempstream = new MemoryStream()) 
        { 
         Image userImage = //method that returns Drawing.Image from byte[]; 
         userImage.Save(tempstream, ImageFormat.Png); 
         tempstream.Seek(0, SeekOrigin.Begin); 
         stream.Seek(0, SeekOrigin.Begin); 
         tempstream.WriteTo(stream); 
        } 

        zipFile.AddEntry(pictureName, stream); 
       } 

       zipFile.Save(Response.OutputStream); 
       } 

      } 

     this.Response.End(); 
     return RedirectToAction("Home"); 
     } 

此代碼可用於上傳和導出一(1)張圖片。但是,將多個圖像上傳到數據庫並嘗試將其全部導出後,生成的Zip文件將只包含最新上傳圖像的數據。所有其他圖像名稱都將出現在zip文件中,但它們的文件大小將爲0,它們只是空文件。

我猜我的問題與MemoryStreams有關(或者我錯過了一些簡單的東西),但是據我所知,通過代碼遍歷,圖像被從數據庫中提取出來被成功添加到zip文件中...

回答

4

您對stream.Seek(0,SeekOrigin.Begin)的調用正在使用最新的圖像數據覆蓋每次迭代的流內容。試試這個:

using (ZipFile zipFile = new ZipFile()) 
{ 
    foreach (var userPicture in userPictures) 
    { 
     string pictureName = userPicture.Name + ".png"; 
     using (MemoryStream tempstream = new MemoryStream()) 
     { 
      Image userImage = //method that returns Drawing.Image from byte[]; 
      userImage.Save(tempstream, ImageFormat.Png); 
      tempstream.Seek(0, SeekOrigin.Begin); 
      byte[] imageData = new byte[tempstream.Length]; 
      tempstream.Read(imageData, 0, imageData.Length); 
      zipFile.AddEntry(pictureName, imageData); 
     } 
    } 

    zipFile.Save(Response.OutputStream); 
} 
+0

工作!謝謝!!! – user1449244