0

假设我从数据库中得到了一些 blob。然后我把它们放在字节数组中。例如:

Byte[] lol1=(Byte[])reader["data1"];
Byte[] lol2=(Byte[])reader["data2"];

现在我如何将这些字节数组作为文件写入 zip 并从 C# 中的浏览器下载它作为文件?

// 为清楚起见进行编辑

“Manager.cs”文件中的相关代码如:

    public Byte[] FileDownload(string userName)
    {
        try
        {
            MySqlDataReader reader = new MySqlCommand("SELECT veri FROM veriler WHERE kullanici_id = (SELECT id FROM uyeler WHERE kullanici_adi='" + userName + "')", con).ExecuteReader();
            MemoryStream ms = new MemoryStream();
            GZipStream gzs = new GZipStream(ms, CompressionMode.Compress);
            while (reader.Read())
                gzs.Write((Byte[])reader["veri"], 0, ((Byte[])reader["veri"]).Length);
            return ms.ToArray();
        }
        catch (Exception)
        {
            return Encoding.UTF8.GetBytes(string.Empty);
        }
    }

“DataDown.aspx.cs”文件中的相关代码如:

protected void download_Click(object sender, EventArgs e)
{
    Response.AddHeader("Content-type", ContentType);
    Response.AddHeader("Content-Disposition", "attachment; filename=Archive.zip");
    Response.BinaryWrite(new Manager().FileDownload(Session["user"].ToString()));
    Response.Flush();
    Response.End();
}

它返回一个 .zip 文件,该文件是其中唯一的文件。它必须是两个文件。此外,这一文件已损坏。

4

1 回答 1

2

要干净利落,您需要System.IO.Compression,它仅在 .Net 4.5 向前版本中可用。

string blobName = "data1";
string zipName = "database.zip";
Byte[] blob = (Byte[])reader[blobName];

using(MemoryStream zs = new MemoryStream())
{
  // Build the archive
  using(System.IO.Compression.ZipArchive zipArchive = new ZipArchive(zs, ZipArchiveMode.Create, true))
  {
    System.IO.Compression.ZipArchiveEntry archiveEntry = zipArchive.CreateEntry(blobName);
    using(Stream entryStream = archiveEntry.Open())
    {
      entryStream.Write(blob, 0/* offset */, blob.Length);
    }
  }

  //Rewind the stream for reading to output.
  zs.Seek(0,SeekOrigin.Begin);

  // Write to output.
  Response.Clear();
  Response.ContentType = "application/zip";
  Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", zipName));
  Response.BinaryWrite(zs.ToArray());
  Response.End();
 }

如果您的数据提供程序支持将 blob 作为流打开,您可能可以避免将条目读取到缓冲区中,而是使用Stream.CopyTo()

于 2013-10-02T16:06:18.583 回答