我在 MVC3 中使用心爱的 DotNetZip 归档库动态生成一个 Zip 文件,其中包含来自存储在数据库中的二进制文件的 .png 图像。然后我将生成的 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 文件中,但它们的文件大小将为 0,并且它们只是空文件。
我猜我的问题与 MemoryStreams (或者我遗漏了一些简单的东西)有关,但据我通过单步执行代码可以看出,图像正在从数据库中提取并被添加到zip文件成功...