I have an MVC application that shows a list of files for download. The user selects the files with a checkbox and these are generated as PDF”s on the server side using the Pechkin library.
My problem is that when downloading more than one file, I’m getting the error that “Server cannot clear headers after HTTP headers have been sent.” which I realise is because I can only send a single HTTP response back to the client, but I’m not sure how to go about fixing this.
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();
}
What’s the pattern that I should be using to accomplish this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can zip all selected files and send it across. There is library available for same on codeplex called DotNetZip
This is how you can zip it.
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");
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0