我正在尝试创建一个工具,它可以在我的服务器上获取图像,并将它们以zip文件的形式下载给用户。这些图像是Sitecore媒体项目,我从中获取流,并试图将流复制到zip文件。
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true);
foreach (var image in imageItems)
{
try
{
var mediaItem = (MediaItem)image;
var media = MediaManager.GetMedia(mediaItem);
Stream stream = media.GetStream();
var extension = mediaItem.Extension;
if (String.IsNullOrEmpty(extension)) continue;
System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(image.Name + "." + extension);
using (System.IO.Stream entryStream = zipItem.Open())
{
stream.CopyTo(entryStream);
}
}
catch (Exception ex) { }
}
var bytesInStream = memoryStream.ToArray();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=SitecoreMediaDownload.zip");
Response.BinaryWrite(bytesInStream);
Response.End();
代码工作没有任何错误,我检查,而调试bytesstream填充(不是空),但当我试图打开/提取zip文件,它说它是无效的。
明白了-必须处理ZipArchive
using (System.IO.MemoryStream zipStream = new System.IO.MemoryStream())
{
using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(zipStream, System.IO.Compression.ZipArchiveMode.Create, true))
{
foreach (var image in imageItems)
{
try
{
var mediaItem = (MediaItem)image;
var media = MediaManager.GetMedia(mediaItem);
var stream = media.GetStream().Stream;
var extension = mediaItem.Extension;
if (String.IsNullOrEmpty(extension)) continue;
System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(image.Name + "." + extension);
using (System.IO.Stream entryStream = zipItem.Open())
{
stream.CopyTo(entryStream);
imagesDownloaded++;
}
}
catch (Exception ex) { }
}
}
zipStream.Position = 0;
litMediaExportOutput.Text = imagesDownloaded + " images downloaded";
Response.Clear();
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader("Content-Disposition", "attachment; filename=SitecoreMediaDownload.zip");
Response.BinaryWrite(zipStream.ToArray());
Response.Flush();
Response.Close();
}
是,将流设置回0位置非常重要,因为如果它仍然指向流的末尾,那么就没有什么可读的了。这里有一个关于这个问题的博客:https://isambarddev.wordpress.com/2016/10/06/inputstreams/