2012-09-24 29 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