创建和流下载C#图像存档zip文件(Create and stream image archive

2019-07-31 20:30发布

我正在使用MVC3心爱DotNetZip归档库生成在其包含巴纽从存储在数据库中的二进制图像飞Zip文件。 然后我流生成的Zip文件出于对用户下载。 (我要保存到数据库之前验证图像数据,所以你可以假定所有的图像数据是有效的)。

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文件,但它们的文件大小是零,他们只是空文件。

我猜我的问题已与MemoryStreams做(或说我失去了一些东西简单),但是就通过代码加强我所知道的,在图像正在从数据库中抽取并正在加入zip文件成功...

Answer 1:

您对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);
}


文章来源: Create and stream image archive zip file for download C#