不要处理MemoryStream
,FileStreamResult
一旦完成将其写入响应,就会小心:
public ActionResult DownloadImagefilesAsZip()
{
var memoryStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddDirectory(Server.MapPath("~/Images"));
zip.Save(memoryStream);
return File(memoryStream, "application/gzip", "images.zip");
}
}
顺便说一句,我建议您编写自定义操作结果来处理此问题,而不是在控制器操作中编写管道代码。不仅您将获得可重用的操作结果,而且请记住您的代码效率非常低=>您正在内存中执行 ZIP 操作,从而将整个 ~/images 目录内容 + zip 文件加载到内存中。如果您在此目录中有很多用户和大量文件,您将很快耗尽内存。
一个更有效的解决方案是直接写入响应流:
public class ZipResult : ActionResult
{
public string Path { get; private set; }
public string Filename { get; private set; }
public ZipResult(string path, string filename)
{
Path = path;
Filename = filename;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var response = context.HttpContext.Response;
response.ContentType = "application/gzip";
using (var zip = new ZipFile())
{
zip.AddDirectory(Path);
zip.Save(response.OutputStream);
var cd = new ContentDisposition
{
FileName = Filename,
Inline = false
};
response.Headers.Add("Content-Disposition", cd.ToString());
}
}
}
进而:
public ActionResult DownloadImagefilesAsZip()
{
return new ZipResult(Server.MapPath("~/Images"), "images.zip");
}