如何下载多个文件? 获取“在发送HTTP标头后服务器无法清除标头”。

我有一个MVC应用程序,显示了一个供下载的文件列表。 用户选择带有复选框的文件,这些文件使用Pechkin库在服务器端生成为PDF。

我的问题是,当下载多个文件时,我收到的错误是“服务器在发送HTTP标头后无法清除标头”。 我意识到这是因为我只能将一个HTTP响应发送回客户端,但我不知道如何解决这个问题。

public ActionResult Forms(FormsViewModel model) { foreach (var item in model.Forms) { if (item.Selected) { CreatePdfPechkin(RenderRazorViewToString(model.FormType, model.Form), model.Name); } } return View(model); } private void CreatePdfPechkin(string html, string filename) { var pechkin = Factory.Create(new GlobalConfig()); var pdf = pechkin.Convert(new ObjectConfig() .SetLoadImages(true).SetZoomFactor(1.1) .SetPrintBackground(true) .SetScreenMediaType(true) .SetCreateExternalLinks(true), html); Response.Clear(); Response.ClearContent(); // error on the next line for the second file to be downloaded Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.pdf; size={1}", filename, pdf.Length)); Response.BinaryWrite(pdf); Response.Flush(); Response.End(); } 

我应该用什么模式来实现这个目标?

您可以压缩所有选定的文件并将其发送出去。 在Codeplex上有一个名为DotNetZip的库可供使用。这就是你可以拉链的方法。

 var outputStream = new MemoryStream(); using (var zip = new ZipFile()) { zip.AddFile("path to file one"); zip.AddFile("path to file two"); zip.AddFile("path to file three"); zip.AddFile("path to file four"); zip.Save(outputStream); } outputStream.Position = 0; return File(outputStream, "application/zip","zip file name.zip");