2015-01-11 84 views
0

我有一個MVC應用程序,顯示下載的文件列表。用戶使用複選框選擇文件,並使用Pechkin庫在服務器端生成PDF文件如何下載多個文件?在HTTP頭被髮送後,「服務器無法清除標題」。

我的問題是,當下載多個文件時,出現「服務器無法後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(); 
    } 

有什麼我應該用它來完成這個模式嗎?

+0

嗨,Iv'e從來沒有帽子建立這樣的功能,但如果我做了,我會嘗試「異步/等待」。這允許您在一次調用中創建多個請求(線程)。自從清除響應之後,錯誤纔有意義。 –

+0

您必須使用AJAX並逐個發送下載請求。 – xwpedram

+1

正如@ xwpedram所提到的,AJAX是一種可能性。全部取決於你感覺更舒適。 –

回答

1

你可以壓縮所有選擇的文件併發送它。 n 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"); 
相關問題