我从数据库中获取数据,转换它,尝试将其压缩并将其返回给用户。我可以为txt和docx文件成功创建一个zip文件,但如果我尝试使用pdf或zip文件,它会失败,并说无法下载文件。尝试从pdf创建zip时,有关代码崩溃的任何想法吗?
if (e.CommandName == "DownloadAttachment")
{
e.Canceled = true;
var item = e.Item as GridEditableItem;
fileId = (int)item.GetDataKeyValue("Unique");
FileData[] allrecords = null;
using (
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["PtcDbModelEntities"].ConnectionString))
{
using (
SqlCommand comm = new SqlCommand("Select Unique1, BinaryData, FileName from PtcDbTracker.dbo.CafFileTable where Unique1=@fileId AND FileName IS NOT NULL", conn))
{
comm.Parameters.Add(new SqlParameter("@fileId", fileId));
conn.Open();
using (var reader = comm.ExecuteReader())
{
var list = new List<FileData>();
while (reader.Read())
{
long len = reader.GetBytes(1, 0, null, 0, 0);
Byte[] buffer = new byte[len];
list.Add(new FileData { BinaryData = buffer, FileName = reader.GetString(2) });
allrecords = list.ToArray();
}
}
conn.Close();
}
}
using (var compressedFileStream = new MemoryStream())
{
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, true))
{
if (allrecords != null)
{
foreach (var record in allrecords)
{
if (record.FileName != null)
{
ZipArchiveEntry zipEntry = zipArchive.CreateEntry(record.FileName, CompressionLevel.NoCompression);
using (var zipEntryStream = zipEntry.Open())
{
zipEntryStream.Write(record.BinaryData, 0, record.BinaryData.Length);
zipEntryStream.Dispose();
}
}
}
}
zipArchive.Dispose();
}
compressedFileStream.Close();
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.BufferOutput = true;
response.AppendHeader("Content-Type", "Application/zip");
response.AppendHeader("Content-Disposition", "Attachment; filename=result.zip");
response.BinaryWrite(compressedFileStream.ToArray());
response.Flush();
response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();
response.Close();
}
}
答案 0 :(得分:0)
在copyto重载中添加特定长度修复了该问题。 ... 使用(var zipEntryStream = zipEntry.Open()) { originalFileStream.CopyTo(zipEntryStream,record.BinaryData.Length); zipEntryStream.Close(); }