如何将 blob 数据写入压缩并以 C# 格式下载
本文关键字:格式 下载 压缩 blob 数据 | 更新日期: 2023-09-27 18:33:40
假设我从数据库中得到了一些blob。然后我把它们放在字节数组中。例如:
Byte[] lol1=(Byte[])reader["data1"];
Byte[] lol2=(Byte[])reader["data2"];
现在如何将这些字节数组作为文件写入 zip 并将其下载为 C# 中的浏览器文件?
为清楚起见,编辑
"管理器.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文件,该文件仅是其中的文件。它必须是两个文件。此外,这一个文件已损坏。
要干净利落地做到这一点,你需要System.IO.Compressing,它仅在.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()