2013-01-31 116 views
1

我正在使用iTextSharp創建PDF報告(文件)並將它們存儲在我的應用程序所在的Web服務器上。我能夠創建該文件,進入存儲文件夾並打開文件沒有問題。注意:用戶不會在創建時自動下載文件 。在Chrome和Firefox中下載損壞的pdf文件

我想讓用戶可以選擇使用按鈕從服務器上下載「舊」報告。 這在IE(10)中工作正常,但在Chrome和Firefox中無法正常工作。我總是收到錯誤消息: 打開此文檔時出錯。該文件已損壞,無法修復。

我有這個圖像按鈕,並點擊我發送用戶到一個通用處理程序(因爲我的頁面包含更新面板)根據this post(現在只使用它部分)。

這是實際下載文件的代碼:

public void ProcessRequest(HttpContext context) 
    { 
     var _fileName = context.Request.QueryString["fileName"]; 

     using (var _output = new MemoryStream()) 
     { 
      //var _fileSeverPath = context.Server.MapPath(_fileName); 
      context.Response.Clear(); 
      context.Response.ContentType = "application/pdf";// "application/pdf"; 
      //context.Response.AppendHeader("Content-Length", _fileName.Length.ToString()); 
      context.Response.AppendHeader("Content-Disposition", string.Format("attachment; filename=" + Path.GetFileName(_fileName))); 

      context.Response.WriteFile(_fileName); 
      context.Response.Flush(); 
      context.Response.Close(); 
      context.Response.End(); 
     } 
    } 

正如我所說的,這個工作在IE罰款,但無法在Chrome和Firefox。 當我在記事本中打開文件時,它接近我在Chrome和Firefox下載時只能獲得大約1/3的文件。

任何建議將不勝感激。一直在努力解決這個現在幾天..

+1

什麼是'_output'好? – usr

+0

嘗試發送一個非常大的(128MB)文件。怎麼了?仍然受損?通過了多少。 – usr

+0

如果服務器上存儲的文件在服務器上打開時是正確的PDF文件,那麼iTextSharp會創建正確的PDF,並且問題是由其他內容引起的。我建議從問題中刪除itextsharp標記。 –

回答

0

好了,最後...我找到了解決方案,它讓我感覺像在同一時間刪除context.Response.Close傻瓜.. (); ...然後一切都完美:)

0

HttpResponse.WriteFile Method (String)

當此方法用於處理大型文件,調用該方法可能會 拋出異常。可以與此 方法一起使用的文件大小取決於Web服務器的硬件配置。有關 的更多信息,請參閱Microsoft知識庫網站上的文章812406,「PRB:Response.WriteFile不能 下載大文件」。

試試這個:

public void ProcessRequest(HttpContext context) 
{ 
    var _fileName = context.Request.QueryString["fileName"]; 
    context.Response.Clear(); 
    context.Response.Buffer = true; 
    context.Response.ContentType = "application/pdf"; 
    context.Response.AppendHeader(
     "Content-Disposition", 
     string.Format("attachment; filename=" + Path.GetFileName(_fileName))); 

    using (var fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read)) 
    { 
     using (var sr = new StreamReader(fs, true)) 
     { 
      int length = (int)fs.Length; 
      byte[] buffer; 

      using (BinaryReader br = new BinaryReader(fs, sr.CurrentEncoding)) 
      { 
       buffer = br.ReadBytes(length); 
       context.Response.BinaryWrite(buffer); 
      } 
     } 
    } 
    context.Response.Flush(); 
    context.Response.Close(); 
    context.Response.End(); 
} 
+0

將讀取數組的末尾。其實,我不相信WriteFile問題是真實的。它會使這個功能無用。這是一個重要的功能。如果它不扔我希望它工作。 – usr

+0

對不起..did無效 –

+0

該文件並不大。 44kb –